|   Home    |    Excel    |    Access   |   Word   |   Outlook   |   FrontPage   |   VBA   |   Downloads   |   Index   |
Word UserForms 2

 

Build an Automatic Document Template for Word

An Introduction to Microsoft Word UserForms
Part 2: Building the UserForm

Introduction

This project will make use of a custom-built dialog box to collect information from the user. Such a custom dialog box, called a UserForm, is created and powered by VBA. This second part of the tutorial deals with building a UserForm to collect all the necessary information needed to complete the document created in the first part of the tutorial.

The document, the UserForm and its accompanying VBA code are contained within the same file. The work of building and coding the UserForm is done using in Word's Visual Basic Editor.

The Visual Basic Editor

For this step you need your document open in Word although the job of building the UserForm will be done in the Visual Basic Editor. Open the Visual Basic Editor by going to Tools > Macro > Visual Basic Editor or use the keyboard shortcut Alt+F11. Unless you have previously made changes here, the Visual Basic Editor opens with an empty code window, with Project Explorer and Properties panes displayed on the left of the main window. If they are not displayed, you can switch on the Project Explorer and Properties panes from the View menu.

The Project Explorer pane is used to navigate through the various objects that you will be working with. It works a bit like Windows Explorer with items grouped into a hierarchy of folders. Here you can see a reference to the documents currently open: the Normal template (which opens and is hidden whenever Word opens) and the letter you are working on. In this example the letter has been given the file name InterviewLetter.doc. Any other open documents will be listed here too.

The Visual Basic Editor showing the Project Explorer pane

In the Project Explorer pane click on the name of your letter document to select it and go to Insert > UserForm. This opens a blank UserForm in the code window, and an entry for the UserForm in the Project Explorer pane, and displays the Toolbox...

The Visual Basic Editor workspace with a blank UserForm

You will use the blank UserForm to build a custom dialog box to help your user complete the letter automatically. The Toolbox contains all the objects you might need to put on your form. If it does not appear either click the Toolbox button on the Visual Basic Editor toolbar or go to View > Toolbox.

Name and Caption the UserForm

In the Project Explorer click UserForm1 to select it and then move to the Properties Window below. The Properties Window shows a list of the properties of the currently selected object, in this case the UserForm itself.

Change the Name property to something more meaningful (object names must not contain spaces and it is customary to prefix form names with the code frm). This example uses the name frmInterviewInvitation.

Change the Caption property to what you would like to see on the form's header bar (the coloured bar at the top of each dialog box and window). This is what the user will see on the dialog box so choose something suitable. This example uses the caption Invitation to Interview.

Changing the Name and Caption properties

When you make these changes you will see corresponding changes to the form itself and to the entries in the Project Explorer pane...

Changes are shown in the Project Explorer pane and on the UserForm

NOTE: You can save your work at any time by going to File > Save or clicking the Save button in either the Visual Basic Editor window or in the Word document window. The UserForm is saved as part of your letter document so, whilst you are still developing your new template, remember to save your changes whenever you close the document.

The next step is to add objects, called Controls to the form. Controls can take the form of a TextBox (used to enter free text), a ComboBox (which offers the user a drop-down list of options, an Option Group (where the user can make a choice by clicking Radio Buttons), a Check Box (where the user places a tick to select an item) or a Command Button (that the user clicks to give an instruction).

There are several other controls in the Visual Basic Editor toolbox and more can be added (such as a Calendar) in the form of ActiveX Controls.

Adding a Text Box

The TextBox toolIf you require only text input from the user, a TextBox control will suffice. Click the TextBox tool on the toolbox then click somewhere on the UserForm. A selected textbox control appears on the UserForm. You can move the control by dragging one of its edges, or change its size by dragging one of the white rectangles around its border. Resize the textbox and drag it to a suitable position on the UserForm, leaving enough room for a label if you plan to add one.

UserForm cursors

The Visual Basic Editor automatically assigns a name to each control you create (e.g. TextBox1). You can make the job of code writing much easier by giving each control a meaningful name. It would be sensible to give the textbox the same name as the bookmark it is related to. It is also conventional, but not essential, to prefix the name with a code that indicates the type of control. In this example, the first textbox will supply text to the RecipientName bookmark so it has been given the name txtRecipientName.

With the textbox selected use the Properties pane to change its Name property to something more relevant.

Adding a Label

The Label ToolMost controls need a label. Click the Label tool on the toolbox and click on the UserForm to create a label. The label's name is not really important in this instance but its content is. You can add content to a label either by clicking inside the label and typing directly into it, or by changing the label's Caption property in the Properties pane.

NOTE: Avoid the temptation to double-click on an object on the UserForm. The Visual Basic Editor interprets this as an instruction to open a code event procedure for the object - handy when you are writing the form's code but you don't need it right now. If you do it accidentally just press Ctrl+Tab until you return to the form design window (or use the Window menu to find it), or double-click the form's name in the Project Explorer pane.

The label can be resized in the same way as the textbox and can contain large amounts of text if necessary. Text will wrap and flow within the label as its shape and size are changed. Make sure that your label is big enough to display all your text. A quick way to resize a label to fit its caption exactly is to double-click one of the resizing handles.

Add, caption and resize a label

Move the label to its correct position and deselect it so you can see how it looks. You can check its final appearance by pressing F5 to preview the form.

Place, deselect and preview the label

Text Box Variations

By default a textbox permits only one line of text. This is fine for most cases (such as the Recipient Name) but sometimes you want the user to be able to enter several lines, as will be the case with the Recipient Address textbox. The control is drawn in the same way but this time set the MultiLine property to True. Normally you would also want to provide a scrollbar so set the ScrollBars property to 2-fmScrollBarsVertical

When entering data into this type of textbox the user should press Ctrl+Enter or Shift+Enter to create a new line. Another option is to set the EnterKeyBehaviour property of the textbox to True. When you do this the user can create a new line in the textbox just by pressing the Enter key.

NOTE: You can offer users hints by making use of a control's ControlTipText property. Enter a short message that you would like to appear as a tool tip when the user pauses their mouse over the control...

Use the ControlTip property to provide hints for the user

Offer Choices with a Combo Box

The ComboBox ToolA combo box provides a simple way to offer a familiar drop-down list of entries from which the user can make a choice. Draw a combo box in the same way as you would a textbox, using the ComboBox tool.

When using a combo box you can choose whether or not to allow the user to make any entry, using the control like a textbox, or to limit their entries to those on your list. If you want to limit the user to the list you must set the MatchRequired property of the combo box to True.

The completed combo box in use

Use the Name property to give your combo box a meaningful name. It is customary to use the prefix cbo when naming combo boxes. This one is called cboInterviewLocation.

NOTE: Most controls have many different property options available. The most commonly used properties are set as defaults. To find out more about any property, click on the property in the Properties pane and press the F1 key.

The task of creating the list itself is performed by a code procedure when the form opens. That will be dealt with later.

Offer Choices with an Option Group

Combo boxes can offer a large list of choices, but when you want to offer the user just a few choices sometimes an option group is more appropriate. An Option Group is a collection of Option Buttons (sometimes called Radio Buttons) placed within a Frame (in fact option buttons on a VBA UserForm do not need to be placed within a frame to work as a group, but it helps the user to understand that they work together).

When building an option group you can choose whether to use Option Buttons, Checkboxes or Toggle Buttons all of which will work the same way. Most commonly option buttons are used. When working as a group the user may only select one option. If they select another the previous choice is deselected.

Tools for building an Option Group

In this example an option group is used to offer the user a choice of greetings with which to end the letter.

First, draw a frame on the UserForm. Don't worry too much about its exact size and shape - you can adjust that later. Use its Caption property to add a label to the top of the frame.

An empty frame with its caption

Now use the OptionButton tool to draw the required number of option buttons inside the frame, filling the descriptive label of each one by entering text into the Caption property or by typing directly into the label.

Use the Name property to give each option button a meaningful name. In my example I have called them optGreeting1 to optGreeting4.  If you have chosen to place your option buttons inside a frame they will automatically behave together as a group. If you prefer not to use a frame - or wish to have more than one group of buttons - make use of the GroupName property of each option button. Controls with the same GroupName will work together as a group even if they are not enclosed inside a frame.

The completed Option Group

Add the Command Buttons

Finally, the form needs some buttons to initiate the various tasks the form has to perform. First, an OK button that will result in the data being transferred to the standard letter; a Cancel button to close the form and throw away the letter if the user changes their mind; and (optionally) a Clear Form button to reset the form to its original values if the user wants to start again.

The Command Button ToolIn VBA these are known as Command buttons. Like the other controls they can be drawn on the form using the toolbox Command Button tool.

Use the Properties pane to give the buttons meaningful names and captions. The convention is to prefix the name of a command button with cmd (e.g. cmdClear, cmdOK and cmdCancel).

Three additional properties are useful when creating command buttons:

The Accelerator property allows you to specify a letter that the user can type as an alternative to clicking the button. This letter should be one of those included in the button's caption. That letter then appears underlined on the caption. To assign an accelerator to a different sort of control, such as a combo box or text box, set the Accelerator property of its label.

The Default property, if set to True, causes that button to be 'clicked' if the user presses the Enter key on their keyboard. This property should only be set on one of the buttons, and would normally be applied to the OK button. Whilst generally useful, you might want to omit this feature if you think the user is likely to press Enter before they have completed the form as it might result in the form closing prematurely. The 'default' button also remains highlighted to indicate its purpose unless the user tabs to a different button.

The Cancel property, if set to True, has the effect of 'clicking' the button to which it is applied when the user presses the Escape (or Esc) key on their keyboard. This feature could usefully be applied to the Cancel button.

Command buttons showing their accelerator letters

That completes the design of the form. Before proceeding any further check its appearance to the user by selecting the form and pressing the F5 key. You may want to alter the form's layout or size before adding the VBA code (although the form's design can be modified at any time).

NOTE: When arranging controls on a form, you can move several controls together, retaining their relative positions, by performing a multiple select. The easiest way to do this is to use the mouse to draw a selection rectangle enclosing the controls you want to select. When you release the mouse all the enclosed controls are selected and can be moved as one.

> > >

Set the Tab Order

A final but important step in setting up the form is to check the Tab Order. This is the order in which the various controls will be visited when a user moves around the form by pressing their Tab key. An illogical order can be extremely frustrating for the user. Go to View > Tab Order to display a dialog box listing all the controls on the form in their current order. Use the buttons to rearrange the order if necessary. You can ignore the Label controls because, although they are listed here, they will be ignored by the tab order.

The completed form is shown below:

The completed UserForm

The Next Step...

In the next step of the tutorial we write the VBA code that will power the form.

>>>GO TO THE NEXT STEP>>>

^ top
   

 

 

 

 

Hit Counter