13
Event-Driven Macros in Excel VBA

Microsoft Excel training courses in London

Embed Size (px)

DESCRIPTION

http://www.macresource.co.uk/fasttrackspecials/msexcel.html Microsoft Excel and VBA training courses in London and throughout the UK

Citation preview

  • 1. Most peoples first introduction to Excelmacros is through the use of therecorder facility which generates aVBA macro that the user can thenmanually launch. Some people thengraduate to editing recorded macrosand perhaps writing their own code.

2. As well as writing macros, Excel VBAalso supports the creation of event-handlers which will execute whencertain events take place in the Excelenvironment. 3. The easiest event handlers to createare those which relate to workbooksand worksheets. 4. When you enter the Visual Basic Editor(VBE), the Project Explorer displays aseries of icons representing each openworkbook and, nested inside each, theworksheets they contain. 5. These icons represent workbook andworksheet objects and Excel VBAallows you to enter special subroutinescalled event handlers directly insidethem. 6. To create an event-handler, simplydouble-click the icon representing theworksheet or workbook in which youwould like to place the event handler. 7. This opens the code window at the topof which two drop-down menus aredisplayed, the one on the left labelled"General" and the one on the right"Declarations". 8. Click on the drop-down on the left andchoose "Workbook" or "Worksheet",depending on which object you areediting. The drop-down on the left willthen display all of the events availablefor event-handlers for that object. 9. Choose an event from the list andExcel will automatically create andevent-handler subroutine with theappropriate name. For example, if theobject is a workbook and you choosethe event "Activate", Excel will createa subroutine called"Workbook_Activate". 10. In addition to workbooks andworksheets, event-handlers can alsobe placed inside Excel UserForms andall of the objects they contain. Tocreate a user form, simply chooseUserForm from the Insert menu then usethe Toolbox to add controls to the form. 11. To create an event handler for anyitem you add to the form, simplydouble-click the object to open thecode window for the form. Excel willthen create the default event-handlerfor that object. If this is not the event-handler you wish to create, choose adifferent event from the drop-downmenu in the top right of the codewindow.