18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Part VI<br />

Programming Excel with VBA<br />

If you click the OK button, notice that it doesn’t close the UserForm as you may expect. This button needs<br />

to have an event-handler procedure in order for it to do anything when it’s clicked. To dismiss the<br />

UserForm, click the close button in its title box.<br />

CROSS-REF<br />

You may prefer to display the UserForm by clicking a CommandButton on your worksheet. See<br />

Chapter 42 for details on attaching a macro to a Worksheet CommandButton.<br />

Creating an event-handler procedure<br />

An event-handler procedure is executed when an event occurs. In this case, you need a procedure to handle<br />

the Click event that’s generated when the user clicks the OK button.<br />

1. Activate the VB Editor. (Pressing Alt+F11 is the fastest way.)<br />

2. Activate the AboutBox UserForm by double-clicking its name in the Project window.<br />

3. Double-click the CommandButton control. The VB Editor activates the code module for the<br />

UserForm and inserts some boilerplate code, as shown in Figure 41.9.<br />

4. Insert the following statement before the End Sub statement:<br />

Unload AboutBox<br />

FIGURE 41.9<br />

The code module for the UserForm.<br />

This statement simply dismisses the UserForm. The complete event-handler procedure is<br />

Private Sub OKButton_Click()<br />

Unload AboutBox<br />

End Sub<br />

Another UserForm Example<br />

The example in this section is an enhanced version of the ChangeCase procedure presented at the beginning<br />

of the chapter. Recall that the original version of this macro changes the text in the selected cells to<br />

uppercase characters. This modified version asks the user what type of case change to make: uppercase,<br />

lowercase, or proper case (initial capitals).<br />

726

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!