User Form objects

As you no doubt know, Excel contains a great many built-in dialog boxes. It is also possible to create custom dialog boxes, also called forms or UserForms. This is done by creating UserForm objects. Figure 3-3 shows the design environment for the Select Special UserForm that we mentioned in Chapter 1.

Figure 3-3. A UserForm dialog box

Figure 3-3. A UserForm dialog box

The large window on the upper-center in Figure 3-3 contains the custom dialog box (named dlgSelectSpecial) in its design mode. There is a floating Toolbox window on the right that contains icons for various Windows controls.

To place a control on the dialog box, simply click on the icon in the Toolbox and then drag and size a rectangle on the dialog box. This rectangle is replaced by the control of the same size as the rectangle. The properties of the UserForm object or of any controls on the form can be changed by selecting the object and making the changes in the Properties window, which we discuss in the next section.

In addition to the form itself and its controls, a UserForm object contains code that the VBA programmer writes in support of these objects. For instance, a command button has a Click event that fires when the user clicks on the button. If we place such a button on the form, then we must write the code that is run when the Click event fires; otherwise, clicking the button does nothing.

For instance, the following is the code for the Close button's Click event in Figure 3-3. Note that the Name property of the command button has been set to cmdClose :

Private Sub cmdClose Click()

Unload Me End Sub

All this code does is unload the form.

Along with event code for a form and its controls, we can also include support procedures within the UserForm object.

Don't worry if all this seems rather vague now. We will devote an entire chapter to creating custom dialog boxes (that is, UserForm objects) later in the book and see several real-life examples throughout the book.

0 0

Post a comment