Chapter 17: Using UserForm Controls. Microsoft Excel VBA Programming
Реклама
Реклама
Chapter 16: UserForm Basics
259
Displaying a UserForm
You display a UserForm by using the UserForm’s Show method in a VBA procedure.
The macro that displays the dialog box must be in a VBA module — not in the
Code window for the UserForm.
The following procedure displays the dialog box named UserForm1:
Sub ShowDialog()
UserForm1.Show
‘ Other statements can go here
End Sub
When Excel displays the dialog box, the ShowDialog macro halts until the user closes the dialog box. Then VBA executes any remaining statements in the procedure. Most of the time, you won’t have any more code in the procedure. As you later see, you put your event-handler procedures in the Code window for the UserForm.
Using information from a UserForm
The VBE provides a name for each control you add to a UserForm. The control’s name corresponds to its Name property. Use this name to refer to a particular control in your code. For example, if you add a CheckBox control to a UserForm named UserForm1, the CheckBox control is named CheckBox1 by default. The following statement makes this control appear with a check mark:
UserForm1.CheckBox1.Value = True
Most of the time, you write the code for a UserForm in the UserForm’s code module. If that’s the case, you can omit the UserForm object qualifier and write the statement like this:
CheckBox1.Value = True
Your VBA code can also check various properties of the controls and take appropriate actions. The following statement executes a macro named
PrintReport if the check box (named CheckBox1) is checked:
If CheckBox1.Value = True Then Call PrintReport
I discuss this topic in detail in Chapter 17.
260
Part IV: Communicating with Your Users
I recommend that you change the default name the VBE has given to your controls to something more meaningful. You might consider naming the check box described above “cbxPrintReport.” Note that I precede the name with a three-letter prefix (for “checkbox”), indicating the type of control. It is a matter of taste whether you think doing so is a good practice.
A UserForm Example
This section’s UserForm example is an enhanced version of the ChangeCase macro from the beginning of the chapter. Recall that the original version of this macro changes the text in the selected cells to uppercase. This modified version uses a UserForm to ask the user which type of change to make: uppercase, lowercase, or proper case.
This dialog box needs to obtain one piece of information from the user: the type of change to make to the text. Because the user has three choices, your best bet is a dialog box with three OptionButton controls. The dialog box also needs two more buttons: an OK button and a Cancel button. Clicking the OK button runs the code that does the work. Clicking the Cancel button causes the macro to finish without doing anything.
This workbook is available at the book’s Web site. However, you get more out of this exercise if you follow the steps provided here and create it yourself.
Creating the UserForm
These steps create the UserForm. Start with an empty workbook.
1. Press Alt+F11 to activate the VBE.
2. If multiple projects are in the Project window, select the project that corresponds to the workbook you’re using.
The VBE inserts a new UserForm object with an empty dialog box.
4. Press F4 to display the Properties window.
5. In the Properties window, change the dialog box’s Caption property to
Change Case.
6. The dialog box is a bit too large, so you may want to click it and use the handles (on the right and bottom sides) to make it smaller.
Step 6 can also be done after you position all the controls in the dialog box.
Chapter 16: UserForm Basics
261
Adding the CommandButtons
Ready to add two CommandButtons — OK and Cancel — to the dialog box?
Follow along:
1. Make sure that the Toolbox is displayed. If it isn’t, choose
View➪Toolbox.
2. If the Properties window isn’t visible, press F4 to display it.
3. In the Toolbox, drag a CommandButton into the dialog box to create a button.
As you see in the Properties box, the button has a default name and caption: CommandButton1.
4. Make sure that the CommandButton is selected. Then activate the
Properties window and change the following properties:
5. Add a second CommandButton object to the UserForm and change the following properties:
6. Adjust the size and position of the controls so your dialog box looks something like Figure 16-4.
Figure 16-4:
The
UserForm with two
Command
Button controls.
262
Part IV: Communicating with Your Users
Adding the OptionButtons
In this section, you add three OptionButtons to the dialog box. Before adding the OptionButtons, you add a Frame object that contains the OptionButtons.
The Frame isn’t necessary, but it makes the dialog box look more professional.
1. In the Toolbox, click the Frame tool and drag it into the dialog box.
This step creates a frame to hold the options buttons.
2. Use the Properties window to change the frame’s caption to Options.
3. In the Toolbox, click the OptionButton tool and drag it into the dialog box (within the Frame).
Doing this creates an OptionButton control.
4. Select the OptionButton and use the Properties window to change the following properties:
Setting the Value property to True makes this OptionButton the default.
5. Add another OptionButton and use the Properties window to change the following properties:
6. Add a third OptionButton and use the Properties window to change the following properties:
7. Adjust the size and position of the OptionButtons, Frame, and dialog box.
Your UserForm should look something like Figure 16-5.
Chapter 16: UserForm Basics
263
If you’d like a sneak preview to see what the UserForm looks like when it’s displayed, press F5. None of the controls are working yet, so you need to click the red “X” in the title bar to close the dialog box.
Figure 16-5:
This is the
UserForm after adding three Option
Button controls inside a
Frame control.
The Accelerator property determines which letter in the caption is underlined — more important, it determines what Alt-key combination selects that control. For example, you can select the Lower Case option by pressing Alt+L because the L is underlined. Accelerator keys are optional, but some users prefer to use the keyboard to navigate dialog boxes.
You may wonder why the OptionButtons have accelerator keys but the
CommandButtons go without. Generally, OK and Cancel buttons never have accelerator keys because they can be accessed from the keyboard. Pressing
Enter is equivalent to clicking OK because the control’s Default property is True. Pressing Esc is equivalent to clicking Cancel because the control’s
Cancel property is True.
Adding event-handler procedures
Now it’s time to make the UserForm actually do something. Here’s how to add an event-handler procedure for the Cancel and OK buttons:
1. Double-click the Cancel button.
VBE activates the Code window for the UserForm and inserts an empty procedure:
Private Sub CancelButton_Click()
The procedure named CancelButton_Click is executed when the Cancel button is clicked, but only when the dialog box is displayed. In other words, clicking the Cancel button when you’re designing the dialog box
264
Part IV: Communicating with Your Users
won’t execute the procedure. Because the Cancel button’s Cancel property is set to True, pressing Esc also triggers the CancelButton_Click procedure.
2. Insert the following statement inside the procedure (before the End
Sub statement):
Unload UserForm1
This statement closes the UserForm (and removes it from memory) when the Cancel button is clicked.
3. Press Shift+F7 to return to the UserForm.
4. Double-click the OK button.
VBE activates the code window for the UserForm and inserts an empty
Sub procedure called
Private Sub OKButton_Click()
When the UserForm is displayed, clicking OK executes this procedure.
Because this button has its Default property set to True, pressing Enter also executes the OKButton_Click procedure.
5. Enter the following code inside the procedure:
Private Sub OKButton_Click()
Dim WorkRange As Range
‘ Process only text cells, no formulas
On Error Resume Next
Set WorkRange = Selection.SpecialCells _
(xlCellTypeConstants, xlCellTypeConstants)
‘ Upper case
If OptionUpper Then
For Each cell In WorkRange
cell.Value = UCase(cell.Value)
Next cell
End If
‘ Lower case
If OptionLower Then
For Each cell In WorkRange
cell.Value = LCase(cell.Value)
Next cell
End If
‘ Proper case
If OptionProper Then
For Each cell In WorkRange
cell.Value = Application. _
WorksheetFunction.Proper(cell.Value)
Chapter 16: UserForm Basics
265
Next cell
End If
Unload UserForm1
End Sub
The preceding code is an enhanced version of the original ChangeCase macro that I present at the beginning of the chapter. The macro consists of three separate blocks of code. This code uses three If-Then structures; each one has a For Each loop. Only one block is executed, determined by which
OptionButton the user selects. The last statement unloads (closes) the dialog box after the work is finished.
Here’s something kind of odd. Notice that VBA has a UCase function and an LCase function, but it doesn’t have a function to convert text to proper case. Therefore, I use Excel’s PROPER worksheet function (preceded by
Application.WorksheetFunction) to do the proper case conversion. Another option is to use the VBA StrConv function. (See the Help system for details.)
The StrConv function is not available in all Excel versions, so I use the
PROPER worksheet function instead.
Creating a macro to display the dialog box
We’re almost finished with this project. The only thing missing is a way to display the dialog box. Follow these steps to make the procedure that makes the dialog box appear:
1. In the VBE window, choose Insert➪Module.
The VBE adds an empty VBA module (named Module1) to the project.
2. Enter the following code:
Sub ChangeCase()
If TypeName(Selection) = “Range” Then
UserForm1.Show
Else
MsgBox “Select a range.”, vbCritical
End If
End Sub
This procedure is simple. It checks to make sure that a range is selected. If so, the dialog box is displayed (using the Show method). The user then interacts with the dialog box and the code stored in the UserForm’s Code pane is executed. If a range is not selected, the user sees a MsgBox with the text,
“Select a range.”
266
Part IV: Communicating with Your Users
Making the macro available
At this point, everything should be working properly. But you still need an easy way to execute the macro. Assign a shortcut key (Ctrl+Shift+C) that executes the ChangeCase macro:
1. Activate the Excel window via Alt+F11.
3. In the Macros dialog box, select the ChangeCase macro.
4. Click the Options button.
Excel displays its Macro Options dialog box.
5. Enter an uppercase C for the Shortcut key.
See Figure 16-6.
6. Enter a description of the macro in the Description field.
8. Click Cancel when you return to the Macro dialog box.
Figure 16-6:
Assign a shortcut key to execute the Change
Case macro.
After you perform this operation, pressing Ctrl+Shift+C executes the
ChangeCase macro, which displays the UserForm if a range is selected.
You can also make this macro available from the Quick Access toolbar. Rightclick the Quick Access toolbar and choose Customize Quick Access Toolbar.
The Excel Options dialog box appears, and you’ll find the ChangeCase macro listed under Macros (see Figure 16-7). Adding a macro to your Quick Access toolbar works much better in Excel 2010. If the workbook that contains the macro isn’t open, Excel 2010 opens it and runs the macro. In Excel 2007, you get an error if the workbook isn’t open.
Chapter 16: UserForm Basics
267
Figure 16-7:
Adding the
Change
Chase macro to the Quick
Access toolbar.
Testing the macro
Finally, you need to test the macro and dialog box to make sure they work properly:
1. Activate a worksheet (any worksheet in any workbook).
2. Select some cells that contain text.
The UserForm appears. Figure 16-8 shows how it should look.
4. Make your choice and click OK.
If you did everything correctly, the macro makes the specified change to the text in the selected cells.
Figure 16-8:
The
UserForm is in action.
268
Part IV: Communicating with Your Users
Figure 16-9 shows the worksheet after converting the text to uppercase.
Notice that the formula in cell B15 and the date in cell B16 were not changed.
The macro, as you recall, works only with cells that contain text.
Figure 16-9:
The text has been converted to uppercase.
As long as the workbook is open, you can execute the macro from any other workbook. If you close the workbook that contains your macro, Ctrl+Shift+C no longer has any function.
If the macro doesn’t work properly, double-check the preceding steps to locate and correct the error. Don’t be alarmed; debugging is a normal part of developing macros. As a last resort, download the completed workbook from this book’s Web site, and try to figure out where you went wrong.
Chapter 17
Using UserForm Controls
In This Chapter
▶
Understanding each type of dialog box control
▶
Changing each control’s properties
▶
Working with dialog box controls
A
user responds to a custom dialog box (also known as a UserForm) by using the various controls (buttons, edit boxes, option buttons, and so on) that the dialog box contains. Your VBA code then makes use of these responses to determine which actions to take. You have quite a few controls at your disposal, and this chapter tells you about them.
If you worked through the hands-on example in Chapter 16, you already have some experience with UserForm controls. This chapter fills in the gaps.
Getting Started with Dialog Box Controls
In this section, I tell you how to add controls to a UserForm, give them meaningful names, and adjust some of their properties.
Before you can do any of these things, you must have a UserForm, which you get by choosing Insert➪UserForm in the VBE. When you add a UserForm, make sure that the correct project is selected in the Project window (if more than one project is available).
Adding controls
Oddly enough, the VBE doesn’t have menu commands that let you add controls to a dialog box. You must use the floating Toolbox, which I describe in
Chapter 16, to add controls. Normally, the Toolbox pops up automatically when you activate a UserForm in the VBE. If it doesn’t, you can display the
Toolbox by choosing View➪Toolbox.
270
Part IV: Communicating with Your Users
Follow along to add a control to the UserForm:
1. Click the Toolbox tool that corresponds to the control you want to add.
2. Click in the UserForm and drag to size and position the control.
Alternatively, you can simply drag a control from the Toolbox to the
UserForm to create a control with the default dimensions. Figure 17-1 shows a UserForm that contains a few controls.
Figure 17-1:
A UserForm with a few controls added.
A UserForm may contain vertical and horizontal grid lines, which help align the controls you add. When you add or move a control, it snaps to the grid. If you don’t like this feature, you can turn off the grids by following these steps:
2. In the Options dialog box, select the General tab.
3. Set your desired options in the Form Grid Settings section.
Introducing control properties
Every control that you add to a UserForm has properties that determine how the control looks and behaves. You can change a control’s properties at the following two times:
✓ ally, using the Properties window.
✓ code. Changes made at runtime are always temporary; they are made to the copy of the dialog box you are showing, not to the actual UserForm object you designed.
Chapter 17: Using UserForm Controls
271
When you add a control to a UserForm, you almost always need to make some design-time adjustments to its properties. You make these changes in the Properties window. (To display the Properties window, press F4.) Figure
17-2 shows the Properties window, which displays properties for the object selected in the UserForm — which happens to be a CheckBox control.
Figure 17-2:
Use the
Properties window to make design-time changes to a control’s properties.
To change a control’s properties at runtime, you must write VBA code. For example, you may want to hide a particular control when the user clicks a check box. In such a case, you write code to change the control’s Visible property.
Each control has its own set of properties. All controls, however, share some common properties, such as Name, Width, and Height. Table 17-1 lists some of the common properties available for many controls.
Table 17-1
Property
Accelerator
AutoSize
BackColor
BackStyle
Common Control Properties
What It Is
The letter underlined in the control’s caption. The user presses this key in conjunction with the Alt key to select the control.
If True, the control resizes itself automatically based on the text in its caption.
The control’s background color.
The background style (transparent or opaque).
(continued)
272
Part IV: Communicating with Your Users
Table 17-1 (continued)
Property
Caption
Value
Left and Top
Width and Height
Visible
Name
Picture
What It Is
The text that appears on the control.
The control’s value.
Values that determine the control’s position.
Values that determine the control’s width and height.
If False, the control is hidden.
The control’s name. By default, a control’s name is based on the control type. You can change the name to any valid name, but each control’s name must be unique within the dialog box.
A graphics image to display. The image can be from a graphics file, or you can select the Picture property and paste an image that you copied to the Clipboard.
When you select a control, that control’s properties appear in the Properties window. To change a property, just select it in the Properties window and make the change. Some properties give you some help. For example, if you need to change the TextAlign property, the Properties window displays a dropdown list that contains all valid property values, as shown in Figure 17-3.
Figure 17-3:
Change some properties by selecting from a drop-down list of valid property values.
Chapter 17: Using UserForm Controls
273
Dialog Box Controls: The Details
In the following sections, I introduce you to each type of control you can use in custom dialog boxes and discuss some of the more useful properties. I don’t discuss every property for every control because that would require a book that’s about four times as thick (and it would be a very boring book).
The Help system for controls and properties is thorough. To find complete details for a particular property, select the property in the Properties window and press F1. Figure 17-4 shows the online help for the SpecialEffect property — useful for when you make your next blockbuster adventure UserForm.
All the sample files in this section are available at this book’s Web site.
Figure 17-4:
The Help system provides lots of information for each property and control.
274
Part IV: Communicating with Your Users
CheckBox control
A CheckBox control is useful for getting a binary choice: yes or no, true or false, on or off, and so on. Figure 17-5 shows some examples of CheckBox controls.
Figure 17-5:
CheckBox controls.
The following is a description of a CheckBox control’s most useful properties:
✓ by using the keyboard. For example, if the accelerator is A, pressing
Alt+A changes the value of the CheckBox control (from checked to unchecked, or from unchecked to checked).
✓
CheckBox. The cell displays TRUE if the control is checked or FALSE if the control is not checked.
✓ a check mark.
Don’t confuse CheckBox controls with OptionButton controls. They look kind of similar, but they are used for different purposes.
ComboBox control
A ComboBox control is similar to a ListBox control (described later in the
“ListBox control” section). A ComboBox, however, is a drop-down box and displays only one item at a time. Another difference is that the user may be allowed to enter a value that does not appear in the list of items. Figure 17-6 shows two ComboBox controls. The control on the right (for the year) is being used, so it displays its list of options.
Figure 17-6:
ComboBox controls.
Chapter 17: Using UserForm Controls
275
The following is a description of some useful ComboBox control properties: mines which column contains the returned value.
the ComboBox.
✓ combo box. A drop-down list doesn’t allow the user to enter a new value.
✓
ComboBox.
If your list of items is not in a worksheet, you can add items to a ComboBox control by using the AddItem method. More information on this method is in
Chapter 18.
CommandButton control
CommandButton is just a common clickable button. It is of no use unless you provide an event-handler procedure to execute when the button is clicked.
Figure 17-7 shows a dialog box with nine CommandButtons. Two of these buttons feature a clipart image (specified by copying the clipart and then pasting it into the Picture field in the Properties window).
Figure 17-7:
Command
Button controls.
When a CommandButton is clicked, it executes an event-handler procedure with a name that consists of the CommandButton’s name, an underscore, and the word Click. For example, if a command button is named MyButton, clicking it executes the macro named MyButton_Click. This macro is stored in the
Code window for the UserForm.
276
Part IV: Communicating with Your Users
The following is a description of some useful CommandButton control properties:
✓
(Only one of the form’s buttons should have this option set to True.)
✓ button. (Again: Just one button should have this option set to True.)
Frame control
A Frame control encloses other controls. You do so either for aesthetic purposes or to logically group a set of controls. A frame is particularly useful when the dialog box contains more than one set of OptionButton controls.
(See “OptionButton control,” later in this chapter.)
The following list describes some useful Frame control properties:
✓ an empty string if you don’t want the control to display a caption.
Image control
An Image control displays an image. You may want to use an Image control to display your company’s logo in a dialog box. Figure 17-8 shows a dialog box with an Image control that displays a photo of some guy who writes Excel books.
Figure 17-8:
An Image control displays a photo.
Chapter 17: Using UserForm Controls
277
The following list describes the most useful Image control properties:
✓ not match the image size.
When you click the Picture property, you are prompted for a filename.
However, the graphics image (once it’s retrieved) is stored in the workbook.
That way, if you distribute your workbook to someone else, you don’t have to include a copy of the graphics file.
Excel’s clipart collection is a great source of images. Use Insert➪Illustrations➪
Clipart and choose an image to place in your worksheet. Select the image and press Ctrl+C to copy it to the Clipboard. Then activate your UserForm, click the Image control, and select the Picture property in the Properties box. Press
Ctrl+V to paste the copied image. You can then delete the clipart image in the worksheet.
Some graphics images are very large and can make your workbook size increase dramatically. For best results, use an image that’s as small as possible.
Label control
A Label control simply displays text in your dialog box. Figure 17-9 shows a few Label controls. As you can see, you have a great deal of control over the formatting of a Label control.
Figure 17-9:
Label controls are easily molded.
278
Part IV: Communicating with Your Users
ListBox control
The ListBox control presents a list of items from which the user can choose one or more. Figure 17-10 shows a dialog box with two ListBox controls.
Figure 17-10:
ListBox controls.
ListBox controls are very flexible. For example, you can specify a worksheet range that holds the ListBox items, and the range can consist of multiple columns. Or you can fill the ListBox with items by using VBA code. (Did I tell you
I prefer that method?)
If a ListBox isn’t tall enough to display all the items in the list, a scrollbar appears so the user can scroll down to see more items.
The following list is a description of the most useful ListBox control properties:
✓ mines which column contains the returned value.
to display full lines of text when the list is scrolled vertically. If False, the
ListBox may display partial lines of text when it is scrolled vertically.
Note that when this property is True, the actual height of your ListBox may be slightly different, when your UserForm is shown, from what you had set it originally. Visual Basic may adjust the height to ensure that the last entry is entirely visible.
✓ the list.
✓ the ListBox.
Завантажити
Реклама