Creating Event Procedures

Unlike Visual Basic, VBA does not have a pre-defined list of event procedures handy in a control's property sheet. Generally one event is supported per control. For instance, when first showing a VBA dialog, Excel supports an event to initialize the dialog's controls, set focus, and do other things. There are two ways to create the event code. The first one is to create an init procedure for the dialog by writing one in a Module sheet, for instance:

Sub Wiz1_init()

'Set the focus to the edit box for the data range:

DialogSheets("Wiz1").Focus =DialogSheets("Wiz1").[RangeEdit].Name

End Sub

Now, switch back to the dialog editor and select the dialog. Do this by clicking on its edge, or anywhere in its title bar. The entire dialog will be outlined if it was selected properly. Next, right-click the edge or title bar and select Assign Macro. In the next dialog box, pick out the name of the init procedure just created. Now when Excel displays the dialog the init procedure will run before the user sees the dialog box. The advantage of this method is that the writer can control the exact procedure name and where the procedure appears in the module sheet.

The other way to create the procedure is to select the control or dialog and then click the Edit Code button on the Forms toolbar. Excel will create the stub of a procedure, complete with a small commented header. Then add the rest of the code.