Академический Документы
Профессиональный Документы
Культура Документы
Document information
Format conventions
The following format conventions are used in this document:
Computer input that you type is shown in a bold
Courier font
http://www.bristol.ac.uk/
Shortcut keys
The following shortcut keys are used throughout the document:
<Alt><F11>
To open the Visual Basic Editor or to switch between the editor and the
worksheet.
<F4>
To display the properties window for the selected object (for example, a
form or control).
<F7>
From the user form window, press <F7> to select or open the user form
code window.
<Shift><F7>
From the user form code window, press <Shift><F7> to select the
user form window.
Related documentation
The following local documents are available from the Web:
Visual Basic for Excel 97/2000 (document exlvba-t1).
Other books are available:
Writing Excel macros, Steve Roman, (Excel 97 and 2000) O'Reilly http://www.oreilly.com/
Excel 97 Programming for Windows for Dummies, John Walkenbach
Excel 2000 Programming for Dummies, John Walkenbach
Contents
Format Conventions
Shortcut keys
Related documentation
Task 1 Creating a user form......................................................................... 1
Task 2 Adding controls ................................................................................. 2
Task 3 Setting control properties................................................................. 3
Task 4 Initialising controls ........................................................................... 5
Task 5 Event procedures .............................................................................. 6
Task 6 Displaying your custom box............................................................. 7
Task 7 ListBoxes............................................................................................ 8
Task 8 Using variables in label controls...................................................... 9
Task 9 Dealing with numerical input......................................................... 11
Task 10 Performing calculations................................................................. 12
Task 11 Unloading forms............................................................................. 13
Appendix A
Appendix B
Appendix C
Appendix D
Appendix E
Introduction
When only a few pieces of information are required from the user (for example, a text string or a
Yes/No/Cancel answer), then the use of InputBox and MsgBox commands (described in the
document Visual Basic for Excel 97/2000) is adequate. If you need to gather more information for
your Visual Basic application, then Custom dialog boxes (known as User Forms) are required.
These tasks lead you through the steps involved in creating a custom dialog box using the facilities
available in Microsoft Excel's Visual Basic Editor.
Prerequisites
It is essential that you are a competent Excel user and have successfully completed the macro tasks
in Visual Basic for Excel 97/2000 (document exlvba-t1). You will also require access to the
Microsoft Excel 97 or 2000 software.
1.1
1.2
1.3
1.4
From the
Insert
menu, select
UserForm.
A new form,
UserForm1,
is added to
your VBA
project as in
figure 2.
Comments
Unlike most Windows commands, Excels VBE does not have alternative menu
commands to allow you to add controls to a user form. To add controls, you must use
the toolbox.
2.1
The controls toolbox should be displayed when you select the user form (figure 2). If
not, from the View menu, select Toolbox.
2.2
Drag a Label
from the toolbox to the top left hand corner of the user form.
Dont worry about the text or the precise positioning at this stage. For now the label
will contain the text, Label1.
2.3
Drag a TextBox
2.4
to
Add a CommandButton
the bottom right of the user form.
To name and label the controls created in the previous task and explore form layout
options.
You will use the Properties window and the Format menu commands.
Comments
If the Properties window is not displayed; from the View menu, select
Properties window (or press <F4>).
3.1
Select Label1 (click once on the relevant control in your user form).
The properties window (figure 4) displays a table of
properties relevant to that control. The left hand side
gives the property name and the right hand side
contains its value.
3.2
Note
3.3
Figure 4 - properties
window (Label1)
The caption is the text that is displayed in the control on the form.
3.4
From the user form, select the text box added in task 2.3 and set its (Name) property
to OrderNo
3.5
With the text box OrderNo still selected, press <Ctrl> and select the
OrderLabel control.
Both the textbox and label controls should now be selected.
From the Format menu, select Align / Tops.
Take a few moments to examine the other commands available from the Format
menu.
Note
3.6
Controls can also be aligned and sized using the mouse or by adjusting the values
Left, Top and Width in a controls properties window. For precise positioning and
sizing of these controls, see the list of property values in appendix 3.
Click once on the command button to select it and set its (Name) property to
OKButton
Set Caption to OK and Default to True.
3.7
Finally, select the user form, UserForm1 and set its properties:
(Name)
Caption
NewOrderForm
Add new order
There are many properties associated with different control types. The help screens
will explain the purpose of each one. Controls can also be set or altered by
programmed subroutines as we will see later.
4.2
At the current cursor position enter the following code to set the focus to the textbox
control when the form is initialised:
OrderNo.SetFocus
You will add more code to this window after you add the other controls (displayed in
Figure 1) to this form.
5.1
5.2
Method
You will use the Insert Module command and the Show property.
Comments
The procedure used to display the dialog box is stored in a new module.
6.1
6.2
6.3
6.4
Return to your Excel worksheet (click on the workbook icon in the Windows
taskbar).
6.5
6.6
6.7
6.8
6.9
6.10
Highlight and delete any rows you have added whilst testing your code
Switch back to the VBE (press <Alt><F11> or click on the icon in the Windows
taskbar).
Task 7 ListBoxes
Objectives
Method
7.1
7.2
7.3
Note
If you wanted to display additional columns from that range, you could increase the
value of the ColumnCount property.
7.4
When the user of the form selects an option from the list of items, the value of this
option is assigned to the Text property of that control. This property then needs to
be added to column 2 (B) of the Orders worksheet. To do this, double-click on the
OK button and add the following code, immediately above the End Sub statement:
Cells(Row, 2) = ItemBox.Text
7.5
7.6
Note
A ComboBox control could also be used to contain a list of items. For guidance on
populating a combo box, see appendix 1.
To obtain a value from the current workbook and display the result in the form.
You will use the Properties window to insert more controls and you will write code to
update a label control with the unit price of the selected item.
The unit price is contained in the range Items, stored in the Items worksheet.
Using the user form window, add two
label controls
control
8.2
and a textbox
as in figure 7.
8.3
8.4
8.5
Select the Procedure dropdown box (currently displaying Click) and change the
selection to Change.
8.6
Note
Excel 2000 users may prefer to use the FormatCurrency() function as follows:
tCost = FormatCurrency(mCost)
8.7
Switch to your workbook, save and test the form. Check that the unit cost figure
displayed in the form changes when you change the item selection in the item box.
8.8
Note
This example assumes that we will be using a text box to input the quantity value.
Assuming that the minimum and maximum quantity values are known, it might be
9.2
To ensure that the form accepts only numerical input, enter the following code to
blank the value of Quantity if any non-numerical value is entered.
9.3
9.4
To enter the quantity into column 4 (D) of the worksheet, locate the
OKButton_Click() procedure and add the following code, immediately above
the End Sub statement:
Cells(Row, 4) = Quantity.Text
9.5
To enter the unit cost into column 5 (E) of the worksheet, you can use the value
calculated in the ItemBox.Change() procedure (added in task 8.6):
Press <Enter> and type the following:
Cells(Row, 5) = mCost
Cells(Row, 5).NumberFormat = "$#,##0.00"
As the mCost variable is now being used outside a single procedure or function, you
will need to declare it at the top of the module:
Press <Ctrl><Home> to go to the top of the user form code window and insert a
new line.
9.6
9.7
Switch to the worksheet, save and test your form. Try entering a non-numerical value
and then enter a numerical value to check that your quantity and unit cost are entered
into columns D and E correctly.
Note
9.8
10
To apply functions to values collected from a form and update the worksheet.
You will use the user form code window.
An alternative method would be to insert the formulae for Acc. Code and Total
into the worksheet (see Appendix 5).
10.1
From the user form window, double-click on the OK button to return to the
OKButton_Click() procedure.
10.2
10.3
10.4
The account code in column 3 (C) is calculated from the table named Items using
the lookup function. To do this, enter the following code:
acc_code = Application.WorksheetFunction.
VLookup(ItemBox.Text,Range("Items"),4,False)
Cells(Row, 3) = acc_code
Note
The variable acc_code is used to calculate the string containing the result of the
sum. In more complex examples, this could be used to break the string construction
into simpler chunks.
10.5
Finally, tidy up the worksheet, ensuring that all the columns are best-fit by adding
the line:
Columns("A:H").AutoFit
10.6
10.7
Note
To improve this application further you should introduce additional error checking to
deal with the scenario where an entry is not found in the lookup table, on the lines of
the following:
On Error Goto NotFound
acc_code = Application (etc)
Exit Sub
NotFound:
Cells(Row,3) = "Not found"
11
11.1
To create a Cancel or Close button for the user form and perform additional error
checking.
You will use the control toolbox and the VBE user form code window.
The user form was initially displayed using the Show property. To close down or stop
displaying the form the command Unload is used.
From the NewOrderForm (UserForm) window and using the control toolbox,
add a CommandButton
11.2
11.3
Double-click on your Close button to create and insert the code to unload the user
form when this button is selected:
Unload NewOrderForm
11.4
11.5
11.6
From the File menu, select Close and Return to Microsoft Excel.
11.7
Run your macro and test that the cancel command button works.
11.8
12
Appendix A
Combo boxes
Comments This appendix supplies some code to allow you to populate a combo box with a
named range in a workbook.
These notes assume that you have a form containing a combo box named ItemBox.
You should also have a range named Items containing the values you wish to
populate the combo box with.
To populate ItemBox with the values in the first column of the range Items, you
need to write some code that is run when the form is initialised.
Double-click on the user form to go to the UserForm_Initialize() procedure.
Immediately above the End Sub command of this procedure, add the following
code:
Set ItemRange = Range("Items")
nItems = ItemRange.Rows.Count
For r = 1 To nItems
ItemBox.AddItem ItemRange.Cells(r, 1)
Next r
ItemBox.ListIndex = 0
Note
The variable ItemRange is used to refer to the range named Items in the
workbook.
The number of rows in this range is calculated and stored in the variable r.
A fornext loop is then used to add the value of the cell in the first column of each
row, r to the control named ItemBox.
The ListIndex property is used to display the first item in the list (0, not 1).
A-1
Appendix B
Spin buttons
Comments To use a spin button control effectively you need to link it to another control, such as
a textbox, so that when the value of the spin button is altered, the value displayed in
the text box is likewise altered. The text box value must also not be allowed to exceed
the Minimum/Maximum range set by the spin button control properties.
These instructions assume you have a form containing a text box control (named
Quantity) and a spin button control (named SpinButton). In the example
worked through above, this should be placed on the form immediately to the right of
Quantity.
An alternative to the code used above (when the text box value changes) is to not
enter any size checking at this stage. Instead, add the code to the
OKButton_Change procedure and produce a message explaining why the entered
value is not acceptable. This is particularly useful in cases where the code is not
appropriate for text box changes (try setting the minimum value to 2, the maximum
to 10 or greater in the spin button control panel and then using this macro to enter a
quantity of 10).
B-1
Appendix C
Initialising controls
Comments This appendix is provided for those who wish to align and size all the controls in this
exercise precisely.
Left
Top
Width
(Name)
Caption
Left
Top
Width
OrderLabel
Order number:
72
OrderNo
96
72
ItemBox
30
180
72
42
54
72
36
QuantityLabel
Quantity :
Quantity
UnitCost
102
72
72
CancelButton
Close
24
102
72
OKButton
OK
108
102
72
NewOrderForm
192
These control properties can be set by selecting each control in order and working
through the properties window to set the desired properties. As already mentioned the
mouse and the Format menu commands can be used to set the size and position of
controls.
It is also possible to set properties in the UserForm_Initialize procedure as in
the example below.
With ItemBox
.Left = 6
.Top = 30
.Width = 180
End With
NewOrderForm.Height = 144
C-1
Appendix D
Comments
Keyboard shortcuts
Not all computer users use the mouse to select fields when filling in a form or dialog
box. When producing a form for others to use, it is courteous to provide an alternative
method of selecting the controls.
Tabs
The tab order is the order in which the user tabs through controls on the form when
using the keyboard.
To demonstrate the use of tabs within a user form, examine the form created above.
Using the user form window, click once to select the first label control (Order
number:).
Press <Tab> several times and watch the order in which the controls are selected.
This order is defined by the TabIndex property on each control in the order in which
they were added to the form. To rearrange the order, you could select the Tabindex
property for each control in turn and assign the new order.
An easier method is to use the Tab Order window.
From the View menu, select Tab Order and move the window so that you can see
both the user form and this window.
Rearrange the tab order of the controls by selecting a control and using the Move Up
and Move Down buttons as required.
Accelerators
An accelerator assigns a shortcut key to a control on the form.
Cancel and OK buttons do not require accelerators as the <Esc> and <Enter>
keys respectively are generally used as keyboard alternatives to selecting these keys
by mouse.
To assign accelerators to other controls, select the control and use the
Accelerator property. In many cases, you will choose the first letter of the
controls caption. However, where two or more controls share the same initial letter
you may need to use a different letter.
You can also use Visual Basic to set the accelerator property in the
UserForm_Initialize procedure. For example,
OrderLabel.
D-1
Appendix E
Inserting formulae
Comments Task 10 used the figures collected in the user form and performed various
calculations before inputting the result in the worksheet. It would also be possible to
insert the formulae directly into the worksheet so that the formula was recalculated
each time a figure in a dependant cell was altered.
Simple calculations
The Totals column (column F in the worksheet) would contain the simplest
formula (namely =D3*E3 where 3 is the current row). Build this formula up, using
the variable Row, by using the following code:
Cells(Row, 6) = "=D" & Row & "*E" & Row
In the example above (task 10) this line would replace the line entered in task 10.3,
namely:
Cells(Row, 6) = mCost * Quantity.Text
Functions
To build up a more complex formula for inserting into a worksheet, it may be easier
to break the task into smaller chunks, using one or more variables as in the example
below using the current value of the Row variable:
mFormula = "=VLOOKUP(" & "B" & Row & _
",Items,4,False)"
Cells(Row, 3) = mFormula
In the example above (task 10) this line would replace the line entered in task 10.4,
namely:
acc_code = Application.WorksheetFunction. _
VLookup(ItemBox.Text,Range("Items"),4,False)
E-1