Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Introduction to UserForms: Part I

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

Aa155729.offvba(en-us,office.10).gif

AITKENonOffice

LEVEL: New Programmer VBA | UserForms | Word

Customizing the Visual Interface

The goal of the Office developer is - or at least should be - to tailor a custom application as closely as possible to the needs of the client. The application's visual interface is particularly important in this regard, because it's what the user actually sees and works with. While the stock screen elements provided by Office are sometimes all you need, there will be other times when they just don't fit the bill. Fortunately, this isn't a dead end for programmers, because UserForms can be called upon for creating customized dialog boxes and windows that serve just about any imaginable program requirement.

Essentially all of the elements in Windows dialog boxes are available for use on UserForms: text boxes for text display and editing, check boxes for selecting options, buttons for carrying out commands, and so on. With UserForms, you can create dialog boxes that are precisely customized for the needs of your project. In this two-part series, I'll show you how to create and program UserForms. This column covers the visual design aspects of UserForms and presents a simple demonstration. In Part II, I'll cover UserForm code and event procedures, as well as present a more sophisticated demonstration.

UserForms Overview

The basis of a UserForm is the form itself (the screen window), represented by a UserForm object. A UserForm will also contain controls that provide the actual visual interface. If a project contains UserForms, you'll see them listed in the Project Explorer, in the Forms folder.

Each UserForm has a set of properties that control its appearance and behavior, such as color, size, and borders. Each control on a form also has its own set of properties, including a unique name that identifies the control. Controls and the UserForm each have a set of events for detection of user actions, such as mouse clicks and keystrokes. A UserForm can contain procedures, including property procedures to provide the UserForm with custom properties.

UserForm Design

To add a new, blank, UserForm to a project, select UserForm from the VBE Insert menu. A new UserForm is created and displayed for editing, as shown in FIGURE 1.

Aa155729.vba200111pa_f_image002(en-us,office.10).jpg
FIGURE 1: A new UserForm in mint condition.

The empty dialog box in the center, with "UserForm1" in its title bar, is the blank UserForm. You can change its size by pointing at one of the small white handles on its right or bottom edge, and dragging to the new size.

The Toolbox displays in a small window below and to the right of the UserForm. The Toolbox contains icons for the various controls you can place on a form. To its left is the UserForm toolbar.

At the lower left, the Properties window lists the properties for the current object. If the UserForm is selected (as it is in FIGURE 1), the Properties window lists the form's properties. If a control is selected, the window displays that control's properties. You can view the properties alphabetically or by category by clicking one of the tabs at the top of the Properties window.

At the top left of the screen is the Project Explorer window, listing all the components of the current project, including its UserForms. Just below the Project Explorer window's title bar are two buttons (View Code and View Object) that display either the UserForm's code or its visual interface. There's also a Toggle Folders button.

If you scroll through the Properties window, you'll see that a UserForm has many properties. Some properties can be set at design time by using the Properties window, and can also be set in code when the project is running. Some other properties can be set only at design time, and are read-only when the application is running. To display Help information about a property, select the property by clicking its name in the Properties window, then press [F1]. Some of the more important UserForm properties are Caption, which is the text displayed in the title bar; Name, which is the name of the form used when you act on the form in code; and ShowModal, which determines whether the form must be closed before other parts of the application can continue executing.

Placing Controls on a UserForm

A blank UserForm is not much use! To create a usable visual interface, you must place controls on the form. The toolbox provides a set of 14 controls that perform a variety of tasks. These controls should meet just about any programming need. They are described briefly in FIGURE 2, and you can use the VB Help system to explore the details.

Control

Description

Label

Displays text that cannot be edited by the user.

TextBox

Displays text that the user can edit.

ListBox

Displays a list of items from which the user can select.

ComboBox

Combines the function of a TextBox and a ListBox.

CheckBox

Displays an option that can be turned on or off.

OptionButton

Similar to a CheckBox, but only one OptionButton in a group can be "on" at one time. To create a group of OptionButton controls, place a Frame control on the UserForm first, then draw the OptionButton controls on the Frame.

ToggleButton

A button that can be either "up" or "down" permitting the user to select and deselect items.

Frame

Used to group other controls, such as OptionButtons.

CommandButton

Displays a button that's selected by the user to carry out some action.

TabStrip

Displays two or more tabs at the edge of the UserForm, permitting the user to select from multiple "pages."

MultiPage

Does essentially the same thing as a TabStrip, but is easier to use.

ScrollBar

Displays a vertical or horizontal scrollbar on the UserForm.

SpinButton

Increments and decrements numbers by clicking with the mouse.

Image

Displays an image.

FIGURE 2: These are the provided controls.

Each type of control is represented by an icon in the Toolbox. There's also an icon, the arrow at the top left, that you can select to work with controls already placed on the UserForm. If you rest the mouse pointer over an icon, a ToolTip will display describing the associated control. To add a control to the UserForm, click the desired icon. Then to add it at the default size, click on the UserForm where you want to locate the top left corner of the control; to add a custom-sized control, drag it onto the UserForm.

Every type of control has the Name property; this property must be unique for each control on a given form. When you add a control to a form, it's assigned a default name. You should change the default name to something more descriptive of the control's purpose because you'll use this name to refer to the control in your code. It can be useful to prefix each control name with an indication of the type of the control. For example, TextBox controls that are used for entering a person's name might be called "txtFirstName" and "txtLastName." Similarly, OptionButton controls for selecting a color might be called "optGreen," "optYellow," and so on. The only time a control name can be left at its default is when the control won't be referred to in code, as is often the case with Label controls.

In addition to changing the Name property, you'll usually need to make other changes to controls, such as setting other property values and modifying the control's size and position. To work with a control or a group of controls, you must first select it (or them). To select one control, just click it. To select multiple controls, select the first one, then hold down the [Shift] key and click one or more additional controls. You can also select multiple controls by dragging over them.

When a control is selected, it displays handles on its corners and edges. When multiple controls are selected, they all have black handles except for the last one selected, which has white handles. To unselect a control or group of controls, click any other control. To select the UserForm itself, click on the form outside of any control.

When you have selected a control or controls, you can change its position, size, or delete it, as follows:

  • To move the selected control, point at it and drag it to the desired location. For some controls, such as MultiPage, you must point at the control's border to move it.
  • To resize the selected control, point at one of its handles and drag the control to the desired size.
  • To delete the selected control, press [Delete].

Most programmers prefer to design UserForms so that the controls on the form line up with each other, providing a neat and attractive appearance. You can align controls in several ways. The UserForm has a design grid that displays as dots on the form. By default, the edges of controls are forced to align with the grid. In other words, when you add, move, or resize a control, its edges cannot be located between the dots. This simplifies the task of aligning controls and making them the same size as each other.

You can modify the grid spacing, or turn it off altogether. To do so, select Tools | Options to display the Options dialog box, then click the General tab (see FIGURE 3). To change the grid spacing, enter new values in the Width and Height boxes. To turn the grid display on or off, click the Show Grid check box. To turn alignment on or off, click the Align Controls to Grid check box.

Aa155729.vba200111pa_f_image004(en-us,office.10).jpg
FIGURE 3: Set the design grid options in the Options dialog box.

When grid alignment is turned off, you can move and resize controls smoothly, without any restrictions. Changing the grid alignment settings doesn't affect controls that are already on the UserForm, only new controls that you add.

The other way to perform alignment tasks is by using the UserForm toolbar (again, see FIGURE 1), which is displayed by selecting Toolbars from the View menu, then clicking UserForm. Some of the buttons on this toolbar won't be available at all times, depending on how many controls are selected. The buttons on this toolbar perform the tasks shown in FIGURE 4.

Button

Action

Bring to Front

Puts the selected control on top of overlapping controls.

Send to Back

Puts the selected control beneath overlapping controls.

Group

Combines multiple selected controls into a group that can be moved and sized as a single unit.

Ungroup

Breaks a group of controls back into its individual constituent controls.

Align

Select from the drop-down list to align controls with each other, or with the grid.

Center

Select from the drop-down list to center the control vertically or horizontally.

Make Width

Select from the drop-down list to make selected controls the same size.

Zoom

Select a zoom percentage to change the size of all controls on the UserForm (not just selected controls).

FIGURE 4: Actions of the UserForm toolbar buttons.

Control Properties

Each control has a set of properties that determine its appearance and behavior. Some properties, such as Height and Width (which determine a control's size) are common to all or most controls. Other properties are unique to a single control type, or are shared by only a few controls. When you add a control to a form, all of its properties are initialized to default values. In most situations, most of a control's properties will be left at the default settings. Typically, you need to change only a few properties to customize the control as required by the application.

Controls also have a property that holds the control's data, whatever that data might be. You'll use this property in code to retrieve data from the control (for instance, retrieving an option that the user has set using a CheckBox), and also to set the control's data (such as specifying text to display in a TextBox). This is the Value property for many controls. The nature of the data depends on the type of control. FIGURE 5 shows the data returned by the Value property for some controls.

Control

Value Property

OptionButton, CheckBox, and ToggleButton

True, if the option is turned on; False, if it's turned off; and Null, if the option is indeterminate.

TextBox

The text in the box.

ScrollBar and SpinButton

A numerical value indicating the scroll or spin position.

ComboBox and Listbox

The value in the bound column of the current row.

CommandButton

Always False.

FIGURE 5: Data returned by the Value property of various controls.

The Properties window displays the properties of the currently selected control, with the property names in the left column and the current settings in the right column. To change a property, click it, then enter the new property value in the right column. Some properties provide you with a drop-down list of settings from which to choose. Others display a dialog box from which you make a selection. In other cases, you just enter the property value directly.

When multiple controls are selected, the Property window displays only those properties that are common to all selected controls. For example, if you select a TextBox control and a Label control, the Property window will contain the ForeColor property (among others) because both controls have this property. However, the Text property won't be displayed because only the TextBox has it. In this situation, changing a shared property changes the property for all selected controls.

Most control properties can also be set in code. Depending on the specifics of your project, you may prefer to set properties in code (at run time), rather than at design time. Suppose, for example, that your UserForm is named "MyForm," and it contains a CheckBox control named "chkConfirm." The following code turns the CheckBox on (displays a check mark in it):

MyForm.chkConfirm.Value = True

Displaying and Hiding UserForms

After you've designed a UserForm, how do you make use of it in your Office application? There are several steps involved. The following examples assume that the UserForm you designed is named "MyForm." The code will be in a procedure that's part of your project; it won't be part of the UserForm. Create an instance of the UserForm:

Dim TheForm As New MyForm

Set initial values for form control properties (if required):

TheForm.Caption = "Enter User Information"
TheForm.txtName.Value = "Enter your name here" 

Display the form using its Show method:

TheForm.Show

At this point the form will display onscreen, and the user can work with it, entering data, selecting options, and doing whatever else is required. When the user is done with the form, it's hidden by executing the Hide method. This is done by code that's part of the UserForm, typically in the Click event procedure for a button.

Creating a Simple UserForm

You can create the following example in any Office application, but the steps assume that you're using the VBA editor from Microsoft Word. First, open the VBA editor, then select UserForm from the Insert menu to add a new form to the project. Change the form's Name property to MyForm, and its Caption property to A Simple User Form Demo. Add a TextBox control to the form. For this example, you can leave its Name property at the default value of TextBox1. Next, add a CommandButton control to the form, and change its Caption property to OK. Double-click the CommandButton to display the code for its Click event procedure, and add the single statement Hide to the procedure, as shown here:

Private Sub CommandButton1_Click()
  Hide
End Sub

Save the file by pressing [Ctrl][S]. At this point, the UserForm is complete. The next steps involve writing the code to display the form, and making use of the data entered in the TextBox. This code doesn't go in the UserForm, but rather in another project module. In the Project Explorer window, double-click the ThisDocument entry to open its code editing window. Select Procedure from the Insert menu to display the Add Procedure dialog box. Enter TestUserForm in the Name box, then click OK. The editor will insert an empty procedure in the code window where you can add the code shown in FIGURE 6.

Public Sub TestUserControl()
   Dim f As New MyForm
   Dim data As String
  
  f.Show
  
  data = f.TextBox1.Value
  MsgBox "You entered " & data
End Sub

FIGURE 6: Use this code to test the form.

Finally, press [Ctrl][S] to save the file, and switch from the VBE back to the Word document. To run the demonstration, press [Alt][F8] to display the Macros dialog box. The TestUserForm procedure (macro) will be listed there, along with any other defined macros. Click the macro name, then click the Run button to execute the demonstration. The form you created will be displayed (see FIGURE 7). Enter some text in the text box, then click OK. A message box will pop up with the text you entered.

Aa155729.vba200111pa_f_image005(en-us,office.10).gif
FIGURE 7: Running the UserForm demonstration.

Conclusion

This simple demonstration serves as a good introduction to UserForms. I hope it's given you some idea of the potential power of this tool. In Part II, I'll delve further into the capabilities of UserForms, explaining how event procedures and form code can further enhance their usefulness.

Peter G. Aitken has been writing about computers and programming for over 10 years, with some 30 books and hundreds of magazine and trade publication articles to his credit. Recent titles include Office XP Development with VBA [Prentice Hall, 2002] and Teach Yourself Internet Programming with Visual Basic in 21 Days [SAMS, 1998]. Peter is the proprietor of PGA Consulting (http://www.pgacon.com/pga_consulting.htm), providing custom application and Internet development to business, academia, and government since 1994. You can reach him at peter@pgacon.com.

Show:
© 2014 Microsoft