Excel VBA Course Notes: 4. User Forms (File: VBA04-UserForms.xls)
THE COURSE Booking Form
.................................... ...Clavis.
IT Uses a Selection of Controls include the TEXES, COMBO BOXES, OPTION button, Check Boxes and Command Buttons.
............... ..
Description of the form:
THICH TWO SIMPLE TEXES (NAME: AND PhONE :) INTO Which The User CAN Type Free Text, And Two Combo Boxes That Let The User To Pick An Item from the list.
There Are Three Option button.
There are two check boxes (Lunch Required and Vegetarian) that, because they are not grouped in a frame, can both be chosen if required. However, if the person making the booking does not want lunch we do not need to know whether or not They is vegetarian. so, The Vegetarian Check Box is Greyed-Out Until Required.
There Are Three Command Buttons (OK, Cancel and Clear Form) Each of Which Performs a Pre-Defined Function When Clicked.
The Control Properties Settings:
CONTROL
Type
Property
Setting
Userform Userform Name
FRMCOURSEBOOKING
CAPTION
Course Booking form name text box name
TXTName Phone Text Box Name
TXTPHONE Department Combo Box Name
CBodepartment Course Combo Box Name
Cbocourse Level Frame Name
Fralevel
CAPTION
Level Introduction Option Button Name
Optintroduction Intermediate Option Button Name
OptinterMediate Advanced Option Button Name
OptVanced Lunch Required Check Box Name
Chklunch Vegetarian Check Box Namechkvegetarian
Enabled
False Ok Command Button Name
cmdok
CAPTION
OK
DEFAULT
True Cancel Command Button Name
Cmdcancel
CAPTION
Cancel
Cancel
True Clear Form Command Button Name
cmdclearform
Building the form
If you want to build the form yourself, Simply Copy The Layout Shown In The Illustration Above: FOLLOW The Steps Below:
1. Open the workbook That You Want The Form To Belong in (Userforms Like Macros Have to Be attached to a workbook) and switch to the visual basic editor.
2. In The Visual Basic Editor Click The Insert Userform Button (or Go To INSERT> Userform).
3. IF The Toolbox Does Not Appear by Itself (First Click The Form To Make Sure It isn't Hiding) Click The Toolbox Button (or Go to View> Toolbox).
4. To place a control on the form click the appropriate button on the toolbox then click the form. Controls can be moved by dragging them by their edges, or resized by dragging the buttons around their perimeter.
5. To edit the properties of a control, make sure the chosen control is selected then make the appropriate changes in the Properties window. If you can not see the properties window go to View> Properties Window.
6. To Remove a Control from the form, select it and click the delete key on your keyboard.
A Userform Will NOT Actually Do Anything Until The Code That Drives The form and it next step is to write the code triaway the form.
Adding The Code: 1 INITIALISING THE FORM
Initialising the form:
Most forms need some kind of setting up when they open. This may be setting default values, making sure field are empty, or building the lists of combo boxes. This process is called Initialising the Form and it is taken care of by a macro called UserForm_Initialize (in case you are confused by my varying spelling of the word "initialis (z) e", it's because I speak English and VBA speaks American -! but do not worry, VBA will spell it for you). Here's how to Build The Code to Initialise The Course Booking Form: 1. TO View The Form's Code WINDOW Go To View> Code or Click F7.
2. When the code window first opens it contains an empty UserForm_Click () procedure. Use the drop-down lists at the top of the code window to choose UserForm and Initialize. This will create the procedure you need. You can now delete the UserForm_Click () procaute.
3. ENTER The FOLLOWING CODE INTO The Procedure:
Private sub Userform_initialize ()
TXTNAME.VALUE = "" "
TXTPHONE.VALUE = "" "
With cbodepartment
.Additem "Sales"
.Additem "marketing"
.Additem "administration"
.Additem "design"
.Additem "advertising"
.Additem "dispatch"
.Additem "transportation"
End with
CBODEPARTMENT.VALUE = "" "
With cbocourse
.Additem "access"
.Additem "excel"
.Additem "PowerPoint"
.Additem "word"
.Additem "frontpage"
End with
Cbocourse.Value = ""
Optintroduction = TRUE
Chklunch = false
Chkvegetarian = false
TXTNAME.SETFOCUS
End Sub
How the initialise code works:
The purpose of the UserForm_Initialize () procedure is to prepare the form for use, setting the default values for the various controls and creating the lists that the combo boxes will show.These lines set the contents of the two text boxes to empty:
TXTNAME.VALUE = "" "
TXTPHONE.VALUE = "" "
NEXT COME THE INSTRUSTRUCTIONS. First Are Specified, THE INITIAL VALUE OF THE Combo Box Is Set To Empty.
With cbodepartment
.Additem "Sales"
.Additem "marketing"
(AS MANY As Necessary ...)
End with
CBODEPARTMENT.VALUE = "" "
IF Required An Initial Choice Can Be Made from The Option Group, in this case:
Optintroduction = TRUE
Both Check Boxes Are Set To False (I.E. NO Tick). Set to true if you want the check box to apear already ticked:
Chklunch = false
Chkvegetarian = false
Finally, The Focus Is Taken To The First Text Box. This Places The Uses Cursor in The Text Box So That The The The the do not need to click the box before the start to type:
TXTNAME.SETFOCUS
Adding The Code: 2 Making The Buttons Work
There Are Three Command Buttons on The Form and Each Must Be Powered by Its Own Procedure. Starting with The Simple Ons ...
Coding The Cancel Button:
Earlier, we used the Properties Window to set the Cancel property of the Cancel button to True. When you set the Cancel property of a command button to True, this has the effect of "clicking" that button when the user presses the Esc key on THEIR Keyboard. But this alone will not cause anything to happen to the form. You need to create the code for the click Event of the Button That Will, in this case:
1. With the UserForm open for editing in the Visual Basic Editor, double-click the Cancel button. The form's code window opens with the cmdCancel_Click () procedure ready for editing.2. The code for closing a form is very simple. Add a Line of code to the procedure so it looks like this:
Private subcmdcancel_click ()
Unload me
End Sub
Coding The Clear Form Button:
I added a button to clear the form in case the user wanted to change their mind and reset everything, and to make it easier if they had several bookings to make at one time. All it has to do is run the Initialise procedure again. A Macro Can Be Told To Run Another Macro (Or Series of Macros if Necessary) by using the call keyword:
1. Double-Click The Clear Form Button. The form's code window Opens with the cmdclearform_click () Procedure Ready for Editing.
2. Add a line of code to the procedure so it looks like this:
Private sub cmdclearform_click ()
Call userform_initialize
End Sub
Coding the ok button:
This is the piece of code that has to do the job of transferring the user's choices and text input on to the worksheet. When we set the Cancel button's Cancel property to True we also set the OK button's Default property to True. This has of clicking THE OK Button WHEN THE User Presses The Enter (Or Return) Key On Their Keyboard (Providing The "). Here's The code to make the button work:
1. Double-Click The Ok Button. The form's code window Opens with the cmdok_click () Procedure Ready for Editing.
2. Edit The Procedure To Add The Following Code:
Private sub cmdok_click ()
ActiveWorkbook.sheets ("Course Bookings"). Activate
Range ("a1"). Selectdo
If ISEMPTY (Activecell) = False Then
Activecell.offset (1, 0) .select
END IF
LOOP Until ISempty (ActiveCell) = TRUE
ActiveCell.Value = txtname.value
Activecell.offset (0, 1) = txtphone.value
Activecell.offset (0, 2) = CBODEPARTMENT.VALUE
Activecell.offset (0, 3) = cbocours.Value
IF Optintroduction = True Then
Activecell.offset (0, 4) .value = "intro"
Elseif OptinterMediate = True Then
Activecell.offset (0, 4) .value = "interface"
Else
Activecell.offset (0, 4) .value = "ADV"
END IF
If Chklunch = True Then
Activecell.offset (0, 5) .value = "yes"
Else
Activecell.offset (0, 5) .value = "no"
END IF
If Chkvegetarian = TRUE THEN
Activecell.offset (0, 6) .value = "yes"
Else
If Chklunch = False Then
Activecell.offset (0, 6) .value = ""
Else
Activecell.offset (0, 6) .value = "no"
END IF
END IF
Range ("a1"). SELECT
End Sub
How The cmdok_click code works:
The First Two Lines Make Sure That The Correct Workbook Is Active and Moves The Selection To Cell A1:
ActiveWorkbook.sheets ("Course Bookings"). Activate
Range ("a1"). SELECT
The Next Few Lines Moves The Selection Down The Worksheet Until It Finds An Empty Cell:
DO
If ISEMPTY (Activecell) = False Then
Activecell.offset (1, 0) .select
END IF
LOOP Until ISempty (ActiveCell) = TRUE
The Next Four Lines Start to Write The Contents of the form on to the worksheet
ActiveCell.Value = txtname.value
Activecell.offset (0, 1) = txtphone.value
Activecell.offset (0, 2) = CBodepartment.ValueActivecell.offset (0, 3) = Cbocourse.Value
Now We come to the option button.................................... ..
IF Optintroduction = True Then
Activecell.offset (0, 4) .value = "intro"
Elseif OptinterMediate = True Then
Activecell.offset (0, 4) .value = "interface"
Else
Activecell.offset (0, 4) .value = "ADV"
END IF
VBA IF statements are much easier to manage than Excel's IF function. You can have as many options as you want, just insert an additional ElseIf for each one. If there were only two options, you would not need the ElseIf, just the If And else 10 The "Don't forget - the all need an endiff.
There IS Another if Statement for Each Check Box. For the Lunch Required Check Box, A Tick In The Box Means "Yes" The Person Requires Lunch, And no Tick Means "No" they don't.
If Chklunch = True Then
Activecell.offset (0, 5) .value = "yes"
Else
Activecell.offset (0, 5) .value = "no"
END IF
We could use a similar IF statement for the Vegetarian check box, but if the person does not require lunch it is irrelevant whether or it would be wrong to assume that they were not vegetarian simply because they did not they are vegetarian. I any case, NOT Require Lunch. The if statement there. The if statement there, NESTED IF Statement:
If Chkvegetarian = TRUE THEN
Activecell.offset (0, 6) .value = "yes"
Else
If Chklunch = False Then
Activecell.offset (0, 6) .value = ""
Else
Activecell.offset (0, 6) .value = "no"
END IFEND IF
A tick in the box means "Yes" the person is vegetarian. If there is no tick in the box, the nested IF statement looks at the Lunch Required check box. If the Lunch Required check box has a tick in it then no tick in the Vegetarian check box means that the person is not vegetarian so it inserts "No" into the cell. However, if the Lunch Required check box does not have a tick in it, then we do not know whether or not the person is vegetarian ( IT Doesn't Matter Anyway) So The Cell IS LEFT Blank ("").
Finally the selection is takesheet, ready for the next entry:
Range ("a1"). SELECT
Adding the code 3: manipulating the form
Finally, an example of how the controls on a form can be manipulated whilst it is in use. When the control properties were set, the Enabled property of the Vegetarian check box was set to False. When a control is not enabled the user can not enter A Value Into It, Although It Can Hold A Value That Was There Already, And VBA CAN Add, Remove or Change The Value.
We do not need to know whether or not the person is vegetarian (even if they are!) If they are not ordering lunch. So, the Vegetarian check box remains disabled unless a tick is placed in the Lunch Required check box. Then The user is free to tick the vegetarian check box if the want to. if Tick IT We will know That the the the answered "yes" and if They don't we know they has arrive "no".
We can toggle the Enabled property from False to True by having a procedure that runs automatically whenever the value of the Lunch Required check box changes. Fortunately, more controls have a Change procedure and the one we use here is chkLunch_Change (). We'll use this to enable the Vegetarian check box when the Lunch Required check box is ticked, and disable it when the Lunch Required check box is not ticked.There's just one more thing we need to do. Supposing someone ticked the Lunch Required check box, and also ticked the Vegetarian check box. Then they changed their mind and removed the tick from the Lunch Required check box. The Vegetarian check box would be disabled but the tick that was put in earlier would remain.
An Extra line of code can make the tick is removed when Box is disabled. Here's the whole think:
Private sub chklunch_change ()
If Chklunch = True Then
Chkvegetarian.enabled = true
Else
Chkvegetarian.enabled = false
Chkvegetarian = false
END IF
End Sub
Opening The Form
The form is now ready for use so it needs to be opened with a simple macro. That can be attached to a custom toolbar button, a command button drawn on the worksheet, or any graphic (right click the graphic and choose Assign Macro). If Necessary, Create A New Module for the Workbook and Add this Procedure:
Sub opencoursebookingform ()
FRMCOURSEBOOKING.SHOW
End Sub