Excel 2010 Bible

(National Geographic (Little) Kids) #1

Part VI: Programming Excel with VBA


848



  1. Use the Toolbox and add a CommandButton object to the UserForm, and use the
    Properties window to change the following properties for the CommandButton:


Property Change To


Name OKButton


Caption OK
Default True


  1. Make other adjustments so that the form looks good to you. You can change the size
    of the form or move or resize the controls.


Testing the UserForm

At this point, the UserForm has all the necessary controls. What’s missing is a way to display the
UserForm. While you’re developing the UserForm, you can press F5 to display it and see how it
looks. To close the UserForm, click the X button in the title bar.

This section explains how to write a VBA Sub procedure to display the UserForm when Excel
is active.


  1. Insert a VBA module by choosing Insert ➪ Module.

  2. In the empty module, enter the following code:
    Sub ShowAboutBox()
    AboutBox.Show
    End Sub

  3. Activate Excel. (Pressing Alt+F11 is one way.)

  4. Choose Developer ➪ Code ➪ Macros to display the Macros dialog box. Or you can
    press Alt+F8.

  5. In the Macros dialog box, select ShowAboutBox from the list of macros and then
    click Run. The UserForm then appears.


If you click the OK button, notice that it doesn’t close the UserForm as you may expect. This but-
ton needs to have an event-handler procedure in order for it to do anything when it’s clicked. To
dismiss the UserForm, click the Close button (X) in its title bar.

Cross-Reference
You may prefer to display the UserForm by clicking a CommandButton on your worksheet. See Chapter 42
for details on attaching a macro to a worksheet CommandButton.
Free download pdf