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.
As well as writing macros, Excel VBAalso supports the creation of event-handlers which will execute whencertain events take place in the Excelenvironment.
The easiest event handlers to createare those which relate to workbooksand worksheets.
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.
These icons represent workbook andworksheet objects and Excel VBAallows you to enter special subroutinescalled event handlers directly insidethem.
To create an event-handler, simplydouble-click the icon representing theworksheet or workbook in which youwould like to place the event handler.
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".
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.
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".
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.
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.