Microsoft Office Tutorials and References
In Depth Information
Handling Multiple UserForm Controls with One Event Handler
Handling Multiple UserForm Controls with One
Event Handler
Every CommandButton on a UserForm must have its own procedure to handle its events. For
example, if you have two CommandButtons, you’ll need two event-handler procedures for the
controls’ click events:
Private Sub CommandButton1_Click()
‘ Code goes here
End Sub
Private Sub CommandButton2_Click()
‘ Code goes here
End Sub
In other words, you can’t assign a macro to execute when any CommandButton is clicked. Each
Click event handler is hard-wired to its CommandButton. You can, however, have each event
handler call another all-inclusive macro in the event-handler procedures, but you’ll need to pass
an argument to indicate which button was clicked. In the following examples, clicking either
CommandButton1 or CommandButton2 executes the ButtonClick procedure, and the
single argument tells the ButtonClick procedure which button was clicked:
Private Sub CommandButton1_Click()
Call ButtonClick(1)
End Sub
Private Sub CommandButton2_Click()
Call ButtonClick(2)
End Sub
If your UserForm has many CommandButtons, setting up all these event handlers can get
tedious. You might prefer to have a single procedure that can determine which button was
clicked and take the appropriate action.
This section describes a way around this limitation by using a class module to define a new class.
This example, named multiple buttons.xlsm , is available on the companion
CD-ROM.
The following steps describe how to re-create the example UserForm shown in Figure 15-21:
 
Search JabSto ::




Custom Search