Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA UserForm Validation: Step-by-Step Guide

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

To validate a VBA UserForm, you check each control's value when the user clicks OK (or before the form closes) and cancel the close if anything is wrong. The shortest working set is: open the form's code module, add a Private Sub cmdOK_Click() handler, test each field with If statements, show a MsgBox naming the problem, and call Cancel = True to keep the form open. That gives you required-field checks, type checks, and range checks without any extra libraries.

This guide covers the practical pattern: where to put the checks, how to test numbers and dates, how to highlight the offending control, and how to avoid the most common traps.

What You'll Need

  • Excel with the Developer tab enabled (File > Options > Customize Ribbon > check Developer).
  • A UserForm with at least a few controls (for example txtName, txtAge, cboDept, and two buttons cmdOK and cmdCancel).
  • Basic familiarity with the VBA editor (Alt+F11) and the Properties window (F4).

Step-by-Step

  1. Name your controls clearly. In the VBA editor, select each control on the form and set its (Name) property in the Properties window. Use prefixes like txt for text boxes, cbo for combo boxes, and opt for option buttons. Clear names make validation code readable and prevent mistakes when you refer to the wrong control.
  2. Decide when validation runs. The most reliable place is the OK button's Click event. You can also validate in the form's QueryClose event to catch the window's X button, but keep the OK button as the primary gate. Avoid validating in Change events because they fire on every keystroke and produce annoying pop-ups.
  3. Open the form's code module. Right-click the UserForm in the Project Explorer and choose View Code, or double-click the form and then double-click the OK button. This creates the cmdOK_Click stub.
  4. Write required-field checks first. For each mandatory control, test for an empty value. For a text box: If Trim(txtName.Value) = "" Then. For a combo box: If cboDept.ListIndex = -1 Then. When a check fails, show a message and exit the sub before the form closes.
    If Trim(txtName.Value) = "" Then
        MsgBox "Please enter a name.", vbExclamation, "Missing data"
        txtName.SetFocus
        Exit Sub
    End If
  5. Validate numbers with IsNumeric. A text box accepts anything, so test before converting. If Not IsNumeric(txtAge.Value) Then catches letters and symbols. Then check the range: If Val(txtAge.Value) < 18 Or Val(txtAge.Value) > 120 Then. Always use Val or CDbl only after IsNumeric passes, otherwise you get a type mismatch error.
  6. Validate dates with IsDate. Use If Not IsDate(txtStart.Value) Then and then compare with CDate(txtStart.Value). Remember that date formats depend on the user's regional settings, so avoid hard-coding formats like "mm/dd/yyyy" in your messages; say "enter a valid date" instead.
  7. Check combo box and list box selections. A combo box with no selection has ListIndex = -1. A list box can have multiple selections; loop through ListCount and test Selected(i) if you need at least one item chosen.
  8. Validate option buttons and check boxes. For a group of option buttons, test each one's Value. If none is True, show a message. For check boxes that require consent, test If Not chkAgree.Value Then.
  9. Use Cancel = True to keep the form open. Inside cmdOK_Click, setting Cancel = True prevents the form from closing. This is the cleanest way to stop the close after a failed check. You can combine it with Exit Sub for clarity.
  10. Highlight the offending control. After showing the message, call SetFocus on the control so the cursor lands there. Optionally change its BackColor to a light red and reset it on the next valid entry. Keep the color change simple; too much color switching looks noisy.
  11. Test the form with edge cases. Enter spaces only, very long text, negative numbers, zero, dates in the past, and no selection at all. Fix any check that lets bad data through or blocks good data.
  12. Write the validated values to the worksheet only after all checks pass. Put the write code at the end of cmdOK_Click, after the last validation block. That way a failed check never leaves partial data on the sheet.

Common Mistakes

  • Validating in the Change event. It fires on every keystroke, so users see pop-ups while typing. Validate on OK instead.
  • Forgetting Trim. A space is not an empty string, so txtName.Value = "" misses a field containing only spaces.
  • Using Val before IsNumeric. Val("abc") returns 0, which may pass a range check and store wrong data.
  • Relying on the form's X button. If you only validate in cmdOK_Click, the user can close with X and skip validation. Add a QueryClose check if that matters.
  • Hard-coding control names after renaming. If you rename a control, update every reference; VBA does not always warn you at compile time for late-bound references.
  • Showing a generic message. "Invalid input" does not tell the user which field is wrong. Name the field and the rule.

Tips

  • Write a small helper function like Function IsBlank(s As String) As Boolean to keep the OK handler short.
  • Set MaxLength on text boxes where a length limit applies; it prevents the error instead of reporting it.
  • Use Tag property on controls to store a friendly field name, then loop through controls for generic validation.
  • Keep validation messages short and actionable: say what to enter, not just what is wrong.
  • Test with the form's Show method from a small test macro so you can iterate quickly.

Troubleshooting

The form closes even when validation fails. Check that you set Cancel = True inside the event that is actually firing. If you validate in cmdOK_Click but the button's Cancel property is set to True in the Properties window, the form may close on Esc; that is separate from your code.

You get a type mismatch error. A control returned text where you expected a number. Add IsNumeric or IsDate before converting, and use Val only after the check passes.

The message appears twice. You may have validation in both cmdOK_Click and QueryClose. Consolidate into one place or guard with a module-level flag.

SetFocus fails. A control must be visible and enabled to receive focus. If it is hidden or disabled, the call errors; check Visible and Enabled first.

Data is written before validation finishes. Move the worksheet write code to the very end of the OK handler, after all checks. If a check fails, Exit Sub prevents the write.

Frequently Asked Questions

Can I validate a UserForm without writing VBA?

No. UserForms are VBA objects, so validation requires code in the form's module. Data validation on the worksheet does not apply to form controls.

Should I use QueryClose or the OK button for validation?

Use the OK button for the main checks. Add QueryClose only if you need to stop the user closing with the X button; it fires for both the X and any programmatic close.

How do I check that a date is in the future?

After confirming IsDate, compare CDate(txtStart.Value) > Date. Remember that Date returns the current system date.

Why does Trim not remove all spaces?

Trim removes leading and trailing spaces but not internal ones. If you need to reject any whitespace-only entry, compare Len(Trim(value)) = 0.

Can I validate multiple fields at once?

Yes, but collect all errors into one message rather than showing a pop-up per field. Build a string and show it once, then focus the first invalid control.

Does validation work the same in Excel for Mac?

The VBA language and UserForm controls are largely the same, but some control properties and the visual layout can differ. Test on the target platform; labels in dialogs may also vary by version and region.