VBA course · Lesson 21 of 33
UserForms: build a data-entry form in VBA
Design a VBA UserForm with text boxes, combo boxes and buttons, fill it on start-up, validate input and write each entry to the next empty row.
A UserForm is a dialog box that you design yourself. Instead of letting people type straight into a sheet, where they can overwrite formulas, put text in a number column or skip a required field, you give them a small window with labelled boxes, drop-down lists and an OK button. Your code checks what they typed and only then writes a clean row into the data sheet.
In this lesson you build a complete expense-claim form from scratch: staff name from a list, date, category, amount, a "receipt attached" tick box and two buttons. Along the way you learn the most useful controls, how to name them, how to fill them when the form opens and how to close a form properly. You need to be comfortable with procedures (Functions and Subs: parameters, ByVal, ByRef and return values) and with finding the last row (Find the last row and build dynamic ranges in VBA); events, which forms are built on, are covered in Events: macros that run by themselves.
Inserting a UserForm
Open the VBA editor with Alt+F11 (Mac: Opt+F11 or Tools > Macro > Visual Basic Editor). In the Project Explorer select your workbook, then choose Insert > UserForm. Three things appear:
- An empty grey form in the design window. Drag its bottom-right handle to resize it.
- The Toolbox, a small floating palette of controls. If it disappears, use View > Toolbox.
- The Properties window (F4), which lists every setting of whatever you have selected.
To add a control, click it in the Toolbox and then draw a rectangle on the form. Double-clicking a control opens the form's code module and creates an event procedure for that control, usually its Click or Change event. Press F7 to jump to the code and Shift+F7 to go back to the design view.
The controls you will use most
| Control | Prefix | Typical use | Key property |
|---|---|---|---|
| Label | lbl | Text that explains a box | Caption |
| TextBox | txt | Free typing: names, amounts, notes | Value / Text |
| ComboBox | cbo | Drop-down list, optionally with typing | Value, List, ListIndex |
| ListBox | lst | Visible list, one or several selections | Value, Selected(), MultiSelect |
| OptionButton | opt | Pick exactly one of a group | Value (True/False) |
| CheckBox | chk | Yes/no choice | Value (True/False) |
| CommandButton | cmd | Run an action: Save, Cancel | Caption, Default, Cancel |
| Frame | fra | Group option buttons visually | Caption |
Name every control before you write code
Every control gets an automatic name such as TextBox1 or CommandButton3. Code that says TextBox3.Value is impossible to read a month later. Before writing any code, select each control and change its (Name) property in the Properties window to a prefix plus a meaning: txtAmount, cboStaff, cmdSave. The prefix tells you the control type when you see the name in code, and the editor's IntelliSense groups all text boxes together when you type txt.
The Caption is something different: it is the visible text on a label, button, check box or the form's title bar. A button can be named cmdSave and have the caption Save claim.
Also rename the form itself, for example to frmExpense, and set its Caption to New expense claim.
The example: an expense-claim form
The workbook has two sheets. Lists holds the staff names in A2:A7 and the categories in C2:C6. Claims is the data sheet with headings in row 1.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Date | Staff | Category | Amount | Receipt | Entered |
| 2 | 02-Dec-2026 | Maria Lopez | Travel | 84.5 | Yes | 02-Dec-2026 09:14 |
Claims sheet before the form is used
Build the form with these controls (names in brackets): a label and combo box for staff (cboStaff), a label and text box for the date (txtDate), a label and combo box for category (cboCategory), a label and text box for the amount (txtAmount), a check box with the caption "Receipt attached" (chkReceipt), a frame captioned "Payment" containing two option buttons "Bank transfer" (optBank) and "Payroll" (optPayroll), and two buttons, cmdSave with caption Save and cmdCancel with caption Cancel. Set cmdSave.Default = True so Enter clicks it and cmdCancel.Cancel = True so Esc clicks it. For the two combo boxes set Style to 2 - fmStyleDropDownList so people can only pick from the list, not type a new spelling.
Filling the form when it opens: UserForm_Initialize
The Initialize event runs once, just before the form appears. It is the place to fill lists and set defaults. Double-click an empty part of the form, choose UserForm in the left drop-down at the top of the code window and Initialize in the right one.
Option Explicit
Private Sub UserForm_Initialize()
Dim wsLists As Worksheet
Dim cell As Range
Set wsLists = ThisWorkbook.Worksheets("Lists")
' Staff names: add one by one so blank cells are skipped
For Each cell In wsLists.Range("A2:A7").Cells
If Len(cell.Value) > 0 Then cboStaff.AddItem cell.Value
Next cell
' Categories: List accepts a whole column of values at once
cboCategory.List = wsLists.Range("C2:C6").Value
' Sensible defaults
txtDate.Value = Format(Date, "dd-mmm-yyyy")
optBank.Value = True
chkReceipt.Value = False
End SubAddItem adds one entry at a time, which lets you skip empty cells or filter names. Assigning a range's .Value to .List loads a whole block in one step; a two-column range would give a two-column list (set ColumnCount to 2). Avoid the RowSource property for lists that grow: it is fixed text such as Lists!A2:A7 and also does not cope well with forms that are opened from other workbooks.
Validating input before you save
Never trust what is typed into a form. The Save button should check every field, tell the person exactly what is wrong, put the cursor in that box and stop. A separate function keeps the click procedure short.
Private Function InputIsValid() As Boolean
InputIsValid = False
If cboStaff.ListIndex = -1 Then
MsgBox "Please choose a staff member.", vbExclamation
cboStaff.SetFocus
Exit Function
End If
If Not IsDate(txtDate.Value) Then
MsgBox "Please type a valid date, for example 02-Dec-2026.", vbExclamation
txtDate.SetFocus
Exit Function
End If
If CDate(txtDate.Value) > Date Then
MsgBox "The expense date cannot be in the future.", vbExclamation
txtDate.SetFocus
Exit Function
End If
If cboCategory.ListIndex = -1 Then
MsgBox "Please choose a category.", vbExclamation
cboCategory.SetFocus
Exit Function
End If
If Not IsNumeric(txtAmount.Value) Then
MsgBox "The amount must be a number.", vbExclamation
txtAmount.SetFocus
Exit Function
End If
If CDbl(txtAmount.Value) <= 0 Or CDbl(txtAmount.Value) > 5000 Then
MsgBox "The amount must be between 0.01 and 5,000.", vbExclamation
txtAmount.SetFocus
Exit Function
End If
InputIsValid = True
End FunctionListIndex is the position of the chosen item, starting at 0, and -1 means nothing is selected. IsDate and IsNumeric check whether the text can be converted, and CDate and CDbl do the conversion. Text box values are always text, so this conversion step matters: if you write txtAmount.Value straight into a cell, Excel may store "84.5" as text and your SUM formulas will ignore it.
Saving to the next empty row
Private Sub cmdSave_Click()
Dim ws As Worksheet
Dim nextRow As Long
If Not InputIsValid() Then Exit Sub
Set ws = ThisWorkbook.Worksheets("Claims")
nextRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row + 1
ws.Cells(nextRow, "A").Value = CDate(txtDate.Value)
ws.Cells(nextRow, "B").Value = cboStaff.Value
ws.Cells(nextRow, "C").Value = cboCategory.Value
ws.Cells(nextRow, "D").Value = CDbl(txtAmount.Value)
ws.Cells(nextRow, "E").Value = IIf(chkReceipt.Value, "Yes", "No")
ws.Cells(nextRow, "F").Value = Now
ws.Cells(nextRow, "G").Value = IIf(optBank.Value, "Bank", "Payroll")
ws.Cells(nextRow, "A").NumberFormat = "dd-mmm-yyyy"
ws.Cells(nextRow, "D").NumberFormat = "#,##0.00"
ws.Cells(nextRow, "F").NumberFormat = "dd-mmm-yyyy hh:mm"
ClearForm
MsgBox "Claim saved in row " & nextRow & ".", vbInformation
cboStaff.SetFocus
End Sub
Private Sub ClearForm()
cboStaff.ListIndex = -1
cboCategory.ListIndex = -1
txtAmount.Value = vbNullString
chkReceipt.Value = False
optBank.Value = True
' The date is kept: people often enter several claims for the same day
End Sub
Private Sub cmdCancel_Click()
Unload Me
End SubThe row is found by jumping up from the bottom of column A, a pattern explained in Find the last row and build dynamic ranges in VBA. Each value is converted to its real type before it is written, so dates are dates and amounts are numbers. After saving, the form stays open and is cleared, ready for the next claim; only Cancel closes it. If your data is an Excel table, you would add a row with ListRows.Add instead (Excel tables in VBA: working with ListObjects).
| A | B | C | D | E | F | G | |
|---|---|---|---|---|---|---|---|
| 1 | Date | Staff | Category | Amount | Receipt | Entered | Payment |
| 2 | 02-Dec-2026 | Maria Lopez | Travel | 84.5 | Yes | 02-Dec-2026 09:14 | Bank |
| 3 | 01-Dec-2026 | Tom Fischer | Meals | 23.9 | No | 02-Dec-2026 09:20 | Payroll |
Claims sheet after saving one more claim (column G added for the payment method)
Showing the form
A form is shown from an ordinary macro in a standard module, which you can then assign to a button on the sheet (Your first macro: Sub, MsgBox, running it and a button):
Option Explicit
Sub ShowExpenseForm()
frmExpense.Show
End SubBy default Show opens the form modal: the person cannot click on the sheet until the form is closed, and the line after Show waits until then. frmExpense.Show vbModeless opens it modeless, so people can scroll the sheet while the form stays on top, and your macro carries on immediately. Modal is simpler and safer for data entry; modeless is useful for search or tool panels.
Unload Me versus Me.Hide
Me inside a form module means "this form". The two ways to close it are different:
Unload Meremoves the form from memory. The nextShowcreates a fresh copy and runsInitializeagain, so lists are refilled and boxes start empty.Me.Hideonly makes it invisible. The form and every value typed into it stay in memory, so the calling macro can still read them, and the nextShowdisplays the same values without runningInitialize.
A common pattern for a dialog that returns an answer is: the form hides itself on OK, the calling macro reads the controls, then unloads it.
Sub AskForRegion()
Dim chosen As String
frmRegion.Show ' waits here until the form is hidden
chosen = frmRegion.cboRegion.Value
Unload frmRegion ' free the memory
If Len(chosen) = 0 Then
MsgBox "No region chosen."
Else
MsgBox "You chose " & chosen & "."
End If
End SubIn frmRegion the OK button runs Me.Hide. If the person closes the form with the red X instead, it is unloaded automatically and the line that reads cboRegion would load a new, empty copy. To control the X button, use the QueryClose event:
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = vbFormControlMenu Then
Cancel = True ' stop the default unload
cboRegion.ListIndex = -1
Me.Hide
End If
End SubA ListBox with several selections
A ListBox shows all its items at once. Set its MultiSelect property to 1 - fmMultiSelectMulti and people can tick several. Reading the choices means looping through the Selected array:
Private Sub cmdShowChoice_Click()
Dim i As Long
Dim picked As String
For i = 0 To lstRegions.ListCount - 1
If lstRegions.Selected(i) Then
picked = picked & lstRegions.List(i) & ", "
End If
Next i
If Len(picked) = 0 Then
MsgBox "Nothing selected."
Else
MsgBox "Selected: " & Left(picked, Len(picked) - 2)
End If
End SubCommon mistakes
- Writing text box values without converting them. Use
CDbl,CLngorCDateafter checking withIsNumericorIsDate, otherwise numbers land in the sheet as text. - Leaving default names.
CommandButton1_Clickstill works after you rename the button tocmdSave, but the old procedure is no longer connected. Rename controls before writing their event code, or rename the procedures to match. - Using
Valueof a ComboBox that has no selection. It returns an empty string orNull; always checkListIndexfirst. - Forgetting that
Unloadloses everything. Read the values you need before unloading. - Tab order. Use View > Tab Order so Tab moves through the boxes top to bottom.
- Not testing with bad input. Type letters into the amount, leave fields empty and press Enter straight away. Good validation survives all of it.
ThisWorkbook, not ActiveWorkbook. Then the form keeps working even when someone has another workbook in front.Check yourself
1. Which event is the right place to fill a ComboBox before the form appears?
Initialize runs once each time the form is loaded, just before it is shown.
2. What does cboStaff.ListIndex = -1 mean?
ListIndex counts from 0 for the first item; -1 means there is no current selection.
3. A user types 84.5 into txtAmount. Why should you write CDbl(txtAmount.Value) to the sheet?
Without the conversion the value can be stored as text and ignored by SUM.
4. What is the difference between Unload Me and Me.Hide?
After Hide, code can still read the controls; after Unload, they are gone.
5. What happens with frmExpense.Show (no arguments)?
Modal is the default; add vbModeless to let people use the sheet while the form is open.