Exlvba t2
Exlvba t2
Format conventions
The following format conventions are used in this document:
Computer input that you type is shown in a bold http://www.bristol.ac.uk/
Courier font
Computer output, menu names and options, Save, Go to, Refresh
buttons, URLs are shown in a Courier font
Text that you must replace is shown in italics Enter your username
Computer keys that you must press are in a bold <Enter>, <n>, <N>, </>
Courier font and enclosed in angle brackets
Instructions for users of other software versions Example text like this
are displayed in a shaded area.
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
Other related documents are available from the web at:
www.bristol.ac.uk/is/learning/documentation/docs-by-category.html#ss
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, see the Related Documentation section for
the location of this document on the web). You will also require access to the Microsoft Excel 97 or
2000 software.
VB Excel 97/2000: Custom dialog boxes
1.1 Open the workbook vbdialog.xls. If you are working in the Computer Centre
training rooms, this file is in the folder C:\User\Excel.
The first sheet, Orders, contains a list of fictitious office supply orders. The other
sheet, Items, contains a list of items and a simple account code lookup table. Take a
few moments to look at the structure of the workbook and the defined ranges.
1.2 The user form you are
going to create will ask
the user to type in an
order number, choose
an item from a list box
and enter the quantity
of items required. The
unit cost for the
selected item will be
displayed on the form.
The finished form will
resemble figure 1.
We will start with a
simplified version with
an Order number
text box and an OK
command button.
Figure 1 - completed user form
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.
Don’t worry about the text or the precise positioning at this stage. For now the label
will contain the text, Label1.
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 Click in the box to the right of (Name), overwrite
Label1 with OrderLabel and press <Enter>.
3.3 Select the Caption value, type Order number: Figure 4 - properties
and press <Enter>. 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 Controls can also be aligned and sized using the mouse or by adjusting the values
Left, Top and Width in a control’s properties window. For precise positioning and
sizing of these controls, see the list of property values in appendix 3.
3.6 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) NewOrderForm
Caption Add new order
The title bar of the user form is amended as you type.
Note 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.
VB Excel 2000: Creating custom dialog boxes (exlvba-t2) 3
VB Excel 97/2000: Custom dialog boxes
End Sub
4.2 To write the code required to
set the initial state of the user
form, click on the
Procedure window
(currently displaying Click)
and select Initialize
(figure 5). Figure 5 - procedure window
4.3 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 From the Window menu, select the user form window,
NewOrderForm (UserForm) (or press <Shift><F7>).
5.2 Double-click on the OK command button to create a procedure to contain the
commands to be run when the OK button is selected.
Complete the code in bold:
Private Sub OKButton_Click()
Sheets("Orders").Activate
If IsEmpty(Range("A2")) then
Rw = 2
Else
Range("A1").End(xlDown).Select
Rw = ActiveCell.Row + 1
End If
Cells(Rw, 1).Select
Cells(Rw, 1) = OrderNo.Text
End Sub
When the OK button is selected, the orders sheet is activated and the cell A2 is
checked to make sure it contains an entry. If not, the orders entered by the user will
start at this point.
If A2 is not empty, then the end of the current column is located and selected. A
variable Rw is then assigned to the row beneath the current selected cell and in turn
selected.
The value for OrderNo is then placed in the first column (column 1).
Task 7 ListBoxes
Objectives To display a list of office items.
Method You will use the control toolbox.
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(Rw, 2) = ItemBox.Text
7.5 Switch to the workbook, save and test the form.
7.6 Close the form (x) and return to theVBE.
Note A ComboBox control could also be used to contain a list of items. For guidance on
populating a combo box, see appendix 1.
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 Close the form (x) and switch back to the VBE.
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.1 Using the forms window, double-click on the Quantity text box control.
The procedure Quantity_Change() is inserted in order to contain the code to be
run whenever the value Quantity is altered.
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 If Not IsNumeric(Quantity.Text) Then
Quantity.Text = ""
End If
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(Rw, 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(Rw, 5) = mCost
Cells(Rw, 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 Enter the following declaration:
Dim mCost As Double
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 You may wish to add additional coding to the Quantity_Change() procedure so
that only whole numbers are accepted.
9.8 Close (x) the form and switch back to the VBE.
10.1 From the user form window, double-click on the OK button to return to the
OKButton_Click() procedure.
10.2 Insert a new line above the End Sub statement.
10.3 To calculate the total in column 6 (F), enter the following code:
Cells(Rw, 6) = mCost * Quantity.Text
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(Rw, 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 Switch to your workbook, save and test the form.
10.7 Switch back to the VBE.
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:
NotFound:
Cells(Rw,3) = "Not found"
11.1 From the NewOrderForm (UserForm) window and using the control toolbox,
add a CommandButton control to the left of the OK button (as task 2.4).
11.2 Modify its properties as follows:
Give the button a name (for example, CancelButton), set the Cancel property
to True and the Caption property to Close (or Cancel).
The Default property should now be set to False.
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 At the beginning of the OKButton.Click procedure insert the following code:
If ItemBox.Text="" or Quantity.Text="" Then
MsgBox "You must specify a valid item and" & _
" a Valid number of items.", VBOkOnly, "AddItems"
Exit Sub
End If
11.5 Click on the Save button in the toolbar.
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 The solution file, vbdialog_complete.xls, contains a working version of this
macro.
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 for…next 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).
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.
Note 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).
Left (distance from the left hand side of the user form)
Top (distance from the top of the user form)
Width (width of the control)
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
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
control’s 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.
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 Rw, by using the following code:
Cells(Rw, 6) = "=D" & Rw & "*E" & Rw
In the example above (task 10) this line would replace the line entered in task 10.3,
namely:
Cells(Rw, 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" & Rw & _
",Items,4,False)"
Cells(Rw, 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)