ExcelTip.com
ExcelTip.com
Account Icon Account Icon Account Icon
Google Exceltip.com
JOIN OUR NEWSLETTER
  and receive for joining:
Free eBook Learn More!
Free Excel ADD-IN
Free Weekly Excel Tip
4 e-books in cd-rom
F1 Formulas & Functions
F1 Formulas & Functions
F1 EXCEL
F1 eBook (Spanish)
F1 EXCEL
Financial Statements.xls
 

» Create User Forms in Microsoft Excel
Tip Contributed by Martin Green.Martin Green, Office Tips is a freelance Access and Excel trainer and developer based in London.

Download Sample Excel file

The Course Booking Form

The Course Booking Form is a simple form illustrating the principles of UserForm design and the associated VBA coding.

It uses a selection of controls including text boxes, combo boxes, option buttons grouped in a frame, check boxes and command buttons.

When the user clicks the OK button their input is entered into the next available row on the worksheet.

Description of the Form:

There are two simple text boxes (Name: and Phone:) into which the user can type free text, and two combo boxes (Department and Course) that let the user to pick an item from the list.

There are three option buttons (Introduction, Intermediate and Advanced) grouped in a frame (Level) so that the user can choose only one of the options.

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 are 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

optAdvanced

Lunch Required

Check Box

Name

chkLunch

Vegetarian

Check Box

Name

chkVegetarian

   

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’t 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 its various controls is created. The next step is to write the code that drives the form itself.

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 don't 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() procedure.

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 instructions for the combo boxes. First of all the contents of the list are specified, then 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 appear already ticked:

chkLunch = False

chkVegetarian = False

Finally, The focus is taken to the first text box. This places the users cursor in the text box so that they do not need to click the box before they 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 ones…

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, close the form. Here's how:

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 Sub cmdCancel_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 they have not used their Tab key to tab to another button). 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").Select

    Do

    If IsEmpty(ActiveCell) = FalseThen

        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) = cboCourse.Value

    If optIntroduction = True Then

        ActiveCell.Offset(0, 4).Value = "Intro"

    ElseIf optIntermediate = True Then

        ActiveCell.Offset(0, 4).Value = "Intermed"

    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, using the active cell (which is in column A) as a reference and moving along the row a cell at a time:

ActiveCell.Value = txtName.Value

ActiveCell.Offset(0, 1) = txtPhone.Value

ActiveCell.Offset(0, 2) = cboDepartment.Value

ActiveCell.Offset(0, 3) = cboCourse.Value

Now we come to the option buttons. These have been placed in a frame on the form so the user can choose only one. An IF statement is used to instruct Excel what to for each option:

If optIntroduction = True Then

    ActiveCell.Offset(0, 4).Value = "Intro"

ElseIf optIntermediate = True Then

    ActiveCell.Offset(0, 4).Value = "Intermed"

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 wouldn't need the ElseIf, just the If and Else would suffice (don't forget - they all need an End If).

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 not they are vegetarian. I any case, it would be wrong to assume that they were not vegetarian simply because they did not require lunch. The IF statement therefore contains a second, 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 If

End 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 taken back to the beginning of the worksheet, 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 cannot 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 don't need to know whether or not the person is vegetarian (even if they are!) if they aren't 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 they want to. If they tick it we will know that they have answered "Yes" and if they don't we know they have answered "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 sure the tick is removed when the box is disabled. Here's the whole thing:

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



Screenshot // Create User Forms in Microsoft Excel

Create User Forms in Microsoft Excel
Rate this tip
12 34 5
  RATING: 3.43
  VIEWS: 542567

READER COMMENTS (view all comments)


vrey good!!!
Leandro wrote on December 31, 1969 19:00 EST
i liked so much this example, its easy to learn...here in Brazil is difficult to find good examples about Vba for Excel.
Im so thankfull..
Really Good!!
Masum wrote on December 31, 1969 19:00 EST
A very easy to understand tutorial, well written and comprehensive in what it does. I would have liked to have read some stuff on TabStrips and multipages though. Or am I being greedy? :)
Date Formating with User Forms
Don Foley wrote on December 31, 1969 19:00 EST
How do I specify a particular Date format. I have a text box on the userform where the user is prompted to enter a date in a particular format ie dd/mm/yy. How do I code and where, to ensure the spreadsheet that the userform updates displays the same format. I have set the System settings to display this format. When I enter the date on the Form in the manner I mention it displays mm/dd/yy on the spread sheet. I would always enter a date in the format dd/mm.
By the way. I have used your Form instructions above to create a greatly expanded UserForm and even having bought a couple of books on VBA since, I find myself refering back to your instructions for their clarity time and time again.
One thing I meant to mention in previous posts is that in the example above you must make an entry in the first box on the form otherwise the spreadsheet data will be over written. In other words you must make an entry in the TextBox, or whatever, that writes to "A1"/first empty cell in column A on the spreadsheet. I have gotten around this by using an if statement which prompts for input and wont allow the form to close and update the spreadsheet until the user makes an entry in this field.
Date Formating with User Forms
Don Foley wrote on December 31, 1969 19:00 EST
How do I specify a particular Date format. I have a text box on the userform where the user is prompted to enter a date in a particular format ie dd/mm/yy. How do I code and where, to ensure the spreadsheet that the userform updates displays the same format. I have set the System settings to display this format. When I enter the date on the Form in the manner I mention it displays mm/dd/yy on the spread sheet. I would always enter a date in the format dd/mm.
By the way. I have used your Form instructions above to create a greatly expanded UserForm and even having bought a couple of books on VBA since, I find myself refering back to your instructions for their clarity time and time again.
One thing I meant to mention in previous posts is that in the example above you must make an entry in the first box on the form otherwise the spreadsheet data will be over written. In other words you must make an entry in the TextBox, or whatever, that writes to "A1"/first empty cell in column A on the spreadsheet. I have gotten around this by using an if statement which prompts for input and wont allow the form to close and update the spreadsheet until the user makes an entry in this field.
help please
timbo27 wrote on December 31, 1969 19:00 EST
I built a userform, I initialized the userform, I coded the userform...all thanks to the advice above.
But how do you show the form on the desktop and when I close and re-open the file....ALL MY WORK IS GONE !!!

Any ideas ??
casino calibaro
Jeniffer wrote on December 31, 1969 19:00 EST
A great site where one can enjoy the thought of a great mind long departed. Cheers for the good work!
mohigan sun casino
Jeniffer wrote on December 31, 1969 19:00 EST
A great site where one can enjoy the thought of a great mind long departed. Cheers for the good work!
Great Tutorial
Will wrote on December 31, 1969 19:00 EST
I've built forms and such in VB and in Access but never in Excel. This is a great tutorial!
Great Tutorial
Will wrote on December 31, 1969 19:00 EST
I've built forms and such in VB and in Access but never in Excel. This is a great tutorial!
XML Search
Marko wrote on December 31, 1969 19:00 EST
Hi. Beautiful content and website design. Sorry for my english. I am from albania.
Gambling Online 2006
Bill wrote on December 31, 1969 19:00 EST
Greetings to all! Excuse for this message, but at you excellent design of a site! Very much it was pleasant to me, I shall come here very often!
Cool Stuff!
Manoj wrote on December 31, 1969 19:00 EST
This is really a cool stuff for the beginners in VBA. It is really help. If possible please provide with some more examples with validation logics that would be great.

Thanks,
Manoj
one problem
waz wrote on December 31, 1969 19:00 EST
if you leave the first field blank, another entry overwrites the last entry
Gr8
Ash wrote on December 31, 1969 19:00 EST
thankyou very much for this helped alot
Nice
Yen wrote on December 31, 1969 19:00 EST
Now, why can't all tutorials be like this!!!????? simple, to the point, and USEFUL!!!!!!!!!!!!!

thanks
Its Wrong
Jerry Francis wrote on December 31, 1969 19:00 EST
If IsEmpty(ActiveCell) = FalseThen
When I copy and paste this it had a error. also up at the top the list the control properties. you should add this captions Clear Form. here is what you have Clear Form
Command Button
Name
cmdClearForm
Thanks it all worked fine
Very Good
Frank wrote on December 31, 1969 19:00 EST
This site is very good. There are many others that just barely scratch the surface. Many books leave out important stuff or say a lot of nothingness. Thanks a bundle.

Frank
run-time error '2110'
WillC wrote on December 31, 1969 19:00 EST
Can't move focus to the control because it is invisible, or not enabled, or of a type that does not accept the focus.
Debug walks through Private Sub UserForm_Initialize() to Private Sub UserForm_Initialize() before this error.
Great Stuff
Greg Northover wrote on December 31, 1969 19:00 EST
This is really good for us beginners... I learnt a lot from this example(I first came across it 12 months ago) I
still refer back to this example because it simplifies how to set up a user form. (would like to see a future version including the option buttons as well)
thanks to people who supplied this.... Great Stuff!!!
Great!!
crey wrote on December 31, 1969 19:00 EST
Exactly what I needed.....told me how and showed me how....Perfect....you should create one for using macromedia programs.
good article
anmol KHANNA wrote on December 31, 1969 19:00 EST
Would be good to add listbox example and datagrid example

Gary wrote on December 31, 1969 19:00 EST
Wonderful example...thanks!!!
Excellent
Sumit wrote on December 31, 1969 19:00 EST
This article is superub for newcomers.It showed me that what I wanted to learn
Cool Stuff
Sumant alias bhaiji wrote on December 31, 1969 19:00 EST
I really liked ,if u cud tell us more of those types of examples?can u
Great stuff
patrick wrote on December 31, 1969 19:00 EST
Just what i was looking for, helps me on the way to my first own made sheet! A great example, simple , but with enough explaination to get me started. Thanks a lot!
Great stuff, but ...
Kim SJ wrote on December 31, 1969 19:00 EST
I would love you to point to all the sources of information one needs to be able to extend it. For example, what other special Subs are there (_click, _initialise, etc.). And where does one find the information about this?

K.
Alfapharm
Alfapharm wrote on December 31, 1969 19:00 EST
I think your site is very good and complete, but the information you have here.

Cheap meds for You!
Plimnaz
Plimnaz wrote on December 31, 1969 19:00 EST
Nice site guys.. didnt have a chance to meet you guys at the conference but hope to see you guys in bing in the near future. stay up.
Widovic
Widovic wrote on December 31, 1969 19:00 EST
Your post very interesting, on it is what is not present on other sites.
cheap viagra
cheap viagra wrote on December 31, 1969 19:00 EST
Good site, men. Thank you!
See U. Elena.
wcmdr
wcmdr wrote on December 31, 1969 19:00 EST
I like this site! Owner you are the great man!
http://hcpsv.pop-search.ru
http://fmob.pop-search.ru
http://zmmue.pop-search.ru
http://hwuwu.pop-search.ru
http://alntt.pop-search.ru

End ^) See you
just wanna ask
rei wrote on December 31, 1969 19:00 EST
is there any codes availabe for searching a specific record and presenting it in the form
History of the USA
Max wrote on December 31, 1969 19:00 EST
History Happens is a collection of music videos about characters from American history. Our goal is to inform and inspire young people that an individual can make a difference-as evidenced by the many acts of courage, endurance and passion that make up the American story.
Great Example
Jai wrote on December 31, 1969 19:00 EST
Hi !

I tried this example and its working fine.

Its really appreciatable. Keep posting more samples.

Take Care

Jai




REGISTERED USERS - Click here to post comments


GUESTS (Click here to register)
Name
Comment Title
Comments

How to Use Financial Statements: A Guide to Understanding the Numbers

Marketing Management

Final Accounting: Ambition, Greed and the Fall of Arthur Andersen

Financial Modeling - 2nd Edition

Millionaire Real Estate Mentor : The Secrets of Financial Freedom through Real Estate Investing

The 22 Immutable Laws of Marketing : Exposed and Explained by the World's Two

RELATED MICROSOFT EXCEL TIPS


Convert PDF Files to Excel






Excel VBA books
Accounting books
Business Plans
MS Office books
Taxes books

VIEW ALL BOOKS


  Advertise With Us                               

Tips

Add-In in VBA | Applications - Word, Outlook in VBA | Array Formulas | Cells, Ranges, Rows, and Columns in VBA | Counting | Custom Functions | Custom Functions in VBA | Database Formulas | Database in VBA | Date & Time Formulas | Date & Time in VBA | Events in VBA | Excel 2003 | Excel Chart | Excel Consolidating | Excel Counting | Excel Custom Functions using VBA | Excel Customizing | Excel Data | Excel Dates | Excel Editing | Excel Files | Excel Filter | Excel Format | Excel Formula | Excel General | Excel Grouping and Outlining | Excel Importing Text Files | Excel Information | Excel Keyboard Shortcuts | Excel Loan Formulas | Excel Macros - VBA | Excel Pivot Tables | Excel Printing | Excel Range Name | Excel Security - Protection | Excel Sorting | Excel Style | Excel Subtotals | Excel Summing | Excel Text | Excel Time | Excel Tools | Excel Worksheet, Workbook | Files, Workbook, and Worksheets in VBA | Financial Formulas | Formating in VBA | General Topics in VBA | Import and Export in VBA | Information Formulas | Keyboard & Other Shortcuts in VBA | Keyboard Formula Shortcuts | Links between Worksheet and Workbooks | Links in VBA | Logical Formulas | Lookup Formulas | Mail - Send and Receive in VBA | Menus, Toolbars, Status bar in VBA | Modules, Class Modules in VBA | Other Q&A Formulas | Printing in VBA | Protecting in VBA | Summing | Text Formulas | User Forms, Input boxes in VBA | Using Loops | Working with Formulas |

Tips by Version

Microsoft Excel 97 | Microsoft Excel 2000 | Microsoft Excel 2002 | All Microsoft Excel Versions | New in Excel 2002 | New in Excel 2003 - Office 11

Website

Home | Tip of Hour | Recommended Tips | Most Viewed Tips | Tips by Version | Submit a Tip | My Tips
Microsoft Excel Tutorials | Excel Links | Write for Us | About Us | Search Results | Tip Archives | Excel Forum | Excel Forum Archives

Excel Book

Excel 97 Book | Excel 2000 Book | Excel 2002 Book | Excel XP Book | Book Store

Terms and Conditions of use
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.

Copyright © 2003 ExcelTip.com
Microsoft, Microsoft Excel is a U.S. registered trademark of Microsoft Corporation
Site Developed By: Varien