2007 MicrosoftВ® Office System Inside Out (Bpg-Inside Out)

When you want to create automation to interact with the user in ways that a message box or input box can’t do, create a dialog box (known in VBA as a UserForm). You can create a custom dialog box in VBA that looks very much like any built-in dialog box you see in Word, Excel, or PowerPoint.

If you’ve ever created form controls in a document or created and formatted AutoShapes on a PowerPoint slide, you already know most of what you need to know to create a custom dialog box. The following subsections walk you through steps to create and use a simple UserForm.

Designing a UserForm

To begin creating your dialog box, select the project (in Project Explorer) to which you want to add your dialog box. Then, on the Insert menu, click UserForm (or select UserForm from the Insert button on the Standard toolbar). When you do, an empty dialog box is created at a default size, as you see here.

If the toolbox that you see in the preceding image doesn’t appear automatically when the form is created, click the Toolbox icon that you see highlighted on the Standard toolbar in this image. The toolbox contains all of the controls you’ll need for creating your form.

Before you start to add controls, take a look at the Properties window. You’ll see a long list of available settings here (as you see in the following image), some of which you might want to customize immediately.

Following are some basic settings in this window that can be particularly helpful.

Notice that you can also customize font, borders, and fill color for the form.

To add controls to the dialog box, in the Toolbox, click the control type you want and then either click or drag to create that control on the form, just as you would do with shapes on a PowerPoint slide. Point to each option in the Toolbox for a ScreenTip indicating the type of control.

In the steps that follow, we’ll create the dialog box you see here.

To create this dialog box, we’ll add the following controls.

To create these controls, do the following.

  1. Click the Label button in the Toolbox (the capital letter A), and then click the form, approximately where you want the label to appear. A label is similar to a text box in a document, so just click into it and replace the text with the text you want (To: for the first label).

    Caution 

    Unlike many programs where you can edit graphic objects, such as text boxes, don’t double-click on a UserForm to edit a control. If you do, you’re likely to accidentally open the Code window for that UserForm and automatically add the default event for the control you double-clicked. Meanwhile, If this happens, just delete the structure for the unwanted event and then double-click the UserForm name in the Project Explorer to return to the form. Control events are discussed later in this section.

  2. Select the label and then, in the Properties window, change its name to something easy to access in a macro. I named this first label labTo. To specify the accelerator keystroke, as you see in the preceding image, type T in the Accelerator field in the Properties window. Remember to press Enter to apply a value after typing in any field in this window.

  3. To size the label to fit the text, with the label selected, click Format and then click Size To Fit. This will help you align the controls when you have them all on the form.

  4. Ctrl+drag to duplicate the label and then set up the other two labels you need, using the same actions in steps 1–3.

  5. Click the TextBox button in the Toolbox and then click the form. Just as you would with any shape, drag to size it as needed.

  6. In the Properties window, name this text box. For ease of reference, I usually give text boxes the same name as their labels, but with a different prefix. So, for example, if I have a label named labTo, I would name the accompanying text box txtTo.

  7. Press Ctrl+drag to duplicate the text box, then rename and resize as needed.

    For the second (Re:) text box, notice that you need it to accept multiple lines. By default, a TextBox control only accepts a single line. To allow text to wrap to multiple lines, in the Properties window, set the MultiLine field to True. If you want to allow the user to add hard returns (by pressing Enter) in that field to start a new line, also change the EnterKeyBehavior field value to True.

  8. Use the same procedure to create and name the two CommandButton controls.

    Note that the text that appears on the command buttons (OK or Cancel) is typed as you would on a text box. Just click in the default text, then delete and replace it with the text you need. Also notice that the text in a label or on a command button is the text in the Caption field in the Properties window, so you can replace the text in that window if you prefer.

  9. Notice that, on the Format menu, you have Align tools as well as Horizontal Spacing and Vertical Spacing options. Select controls as you would shapes on a slide and use these formatting tools to align the controls, as you see in the preceding sample.

    It’s worth noting that the Align options here work similarly to the way they work in Microsoft Visio and not as you may be familiar with from PowerPoint. That is, controls align to the first control you select. The dominant control has white handles when selected, so that you can easily identify the direction in which selected controls will align. (However, holding the Shift key while selecting constrains which controls you can select. If you hold the Ctrl key instead, you can select any controls on the form in any order, and the last object you select will be the dominant control.)

  10. Right-click the form and then click Tab Order. In the Tab Order dialog box, move control names up or down as needed so that an applicable label appears immediately before its related text or combo box control, and so that the controls appear in the order in which you’d want to access them if you were tabbing through the dialog box. For the sample form, my completed Tab Order dialog box looks like the following.

    Note that, if a label doesn’t precede its related field, using the accelerator key on the label won’t access that field.

Once your controls are named and positioned, you’re ready to add the automation you’ll need to use this form.

Automating a UserForm

There are two parts to automating a dialog box, as follows.

Depending on the types of controls that your dialog box includes, the code in your UserForm might get rather complex. For our sample dialog box, however, all we need is code to manage what happens when a command button is clicked. To do this, start by double-clicking the OK button.

When you double-click a control, the code for that control appears with a procedure created for you, using that control’s default event Similar to document-level events (discussed earlier in this chapter), the name of the procedure connects it to a specific event. For command buttons, the default event is the one you’ll usually want. For others, however, you might want to change the default event (for example, the default event for a check box is click, but you might need an event to occur when the value changes rather than when the box is clicked). As with document-level events, the available events in the Procedure list are those available to the type of control you’re automating (the control selected in the Object list).

For the OK button, all you need to do is set it to hide the form. The macro that runs the form will continue to run after the form is hidden by the user. For the Cancel button, however, you’ll want to unload the form and then end code execution (in two separate procedures), so that the macro doesn’t continue to run.

You can refer to a UserForm as Me in code contained in that UserForm. Though you can also refer to the form by name, using Me is handy because you won’t need to change the references if you change the form name. The code for the OK and Cancel buttons would look like this:

Private Sub cmdOK_Click() Me.Hide End Sub Private Sub cmdCancel_Click() Unload Me End Sub

You can end code execution from the preceding event for the Cancel button. However, if you instead add a separate event-the Terminate event for the UserForm-you’ll also account for the user clicking the close button in the title bar of the UserForm instead of using your Cancel command button. This additional event looks like the following.

Private Sub UserForm_Terminate() End End Sub

To create this event, you can simply type it beneath the other events in the Code window for your UserForm. Or, select UserForm from the Objects list at the top of that Code window and then select Terminate from the Procedure list. Note that, when you select UserForm, its default event (Click) will be added to your code. You can simply delete that if you don’t need it.

Note 

To toggle between a UserForm and its code, right-click the form name in Project Explorer and then click View Code or View Object, as needed.

To automate the form in a procedure that you’ll run from a module, set up anything you want to specify about how controls look when the dialog box is launched, then show the dialog box (using the Show method you see in the following sample) and then execute any commands you want for using the information the user adds in a dialog box. Take a look at one possible sample macro for automating the preceding dialog box.

Sub Fax() With frmSample .txtTo.Value = "" .txtRe.Value = "" .Show With ActiveDocument.Tables(1) .Cell(1, 2).Range.Text=frmSample.txtTo.Value .Cell(2, 2).Range.Text=frmSample.txtRe.Value End With End With End Sub

Let’s take a walk through this code.

To learn about adding and automating more complex controls on a dialog box (such as combo box or multipage controls) or to learn other options for automating your UserForms (including what types of procedures you can do directly from the UserForm’s code), see the additional resources recommended in the next section of this chapter.

Note 

Because the macros provided in the preceding section reference UserForms, this code is not included in the sample file  PrimerMacros.bas. Instead, find similar examples of basic UserForms and automation for those forms in the sample file  Sample Macros.dotm, also referenced earlier.

Категории