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.

Intermediate 20 min read

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.

Note. On a Mac, Excel 2016 and later can run UserForms, and recent Microsoft 365 versions also let you design them, but the designer is more limited: fewer controls in the Toolbox, no additional ActiveX controls, and fonts may render at a slightly different size. If a form must work on both systems, design on Windows, keep it simple and test it on a Mac before handing it out.

The controls you will use most

ControlPrefixTypical useKey property
LabellblText that explains a boxCaption
TextBoxtxtFree typing: names, amounts, notesValue / Text
ComboBoxcboDrop-down list, optionally with typingValue, List, ListIndex
ListBoxlstVisible list, one or several selectionsValue, Selected(), MultiSelect
OptionButtonoptPick exactly one of a groupValue (True/False)
CheckBoxchkYes/no choiceValue (True/False)
CommandButtoncmdRun an action: Save, CancelCaption, Default, Cancel
FramefraGroup option buttons visuallyCaption

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.

ABCDEF
1DateStaffCategoryAmountReceiptEntered
202-Dec-2026Maria LopezTravel84.5Yes02-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.

VBA
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 Sub
In the frmExpense code module: fill the lists and set defaults

AddItem 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.

VBA
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 Function
In the frmExpense code module: one function that checks all fields

ListIndex 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

VBA
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 Sub
In the frmExpense code module: the Save and Cancel buttons

The 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).

ABCDEFG
1DateStaffCategoryAmountReceiptEnteredPayment
202-Dec-2026Maria LopezTravel84.5Yes02-Dec-2026 09:14Bank
301-Dec-2026Tom FischerMeals23.9No02-Dec-2026 09:20Payroll

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):

VBA
Option Explicit

Sub ShowExpenseForm()
    frmExpense.Show
End Sub
In a standard module (Insert > Module)

By 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 Me removes the form from memory. The next Show creates a fresh copy and runs Initialize again, so lists are refilled and boxes start empty.
  • Me.Hide only makes it invisible. The form and every value typed into it stay in memory, so the calling macro can still read them, and the next Show displays the same values without running Initialize.

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.

VBA
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 Sub
A modal dialog that asks for a region and returns it to the macro

In 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:

VBA
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 Sub
In the form module: turn the X button into a normal Cancel

A 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:

VBA
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 Sub
Collect every selected region from lstRegions into one text

Common mistakes

  • Writing text box values without converting them. Use CDbl, CLng or CDate after checking with IsNumeric or IsDate, otherwise numbers land in the sheet as text.
  • Leaving default names. CommandButton1_Click still works after you rename the button to cmdSave, but the old procedure is no longer connected. Rename controls before writing their event code, or rename the procedures to match.
  • Using Value of a ComboBox that has no selection. It returns an empty string or Null; always check ListIndex first.
  • Forgetting that Unload loses 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.
Tip. Put the form in the same workbook as the data and refer to sheets through 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?

2. What does cboStaff.ListIndex = -1 mean?

3. A user types 84.5 into txtAmount. Why should you write CDbl(txtAmount.Value) to the sheet?

4. What is the difference between Unload Me and Me.Hide?

5. What happens with frmExpense.Show (no arguments)?