Excel 2019 Bible

(singke) #1

Chapter 44: Creating UserForms


44


This section explains how to write a VBA 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


  1. Press Alt+F11 to activate Excel.

  2. Choose Developer ➪ Code ➪ Macros (or press Alt+F8). The Macro dialog box
    appears.

  3. Select ShowAboutBox from the list of macros, and then click Run. The UserForm
    appears.


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

You may prefer to display the UserForm by clicking a CommandButton on your worksheet. See
Chapter 45 for details on attaching a macro to a worksheet CommandButton.

Creating an event handler procedure
An event handler procedure is executed when an event occurs. In this case, you need a pro-
cedure to handle the Click event that’s generated when the user clicks the OK button.


  1. Press Alt+F11 to activate the VBE.

  2. Activate the AboutBox UserForm by double-clicking its name in the Project
    window.

  3. Double-click the CommandButton control. The VBE activates the code module for
    the UserForm and inserts the Sub and End Sub statements for the button’s click
    event, as shown in Figure 44.9.


FIGURE 44.9
The code module for the UserForm
Free download pdf