Excel VBA UserForm Validation: Step-by-Step Guide
In this article
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 buttonscmdOKandcmdCancel). - Basic familiarity with the VBA editor (Alt+F11) and the Properties window (F4).
Step-by-Step
- 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 liketxtfor text boxes,cbofor combo boxes, andoptfor option buttons. Clear names make validation code readable and prevent mistakes when you refer to the wrong control. - Decide when validation runs. The most reliable place is the OK button's Click event. You can also validate in the form's
QueryCloseevent to catch the window's X button, but keep the OK button as the primary gate. Avoid validating inChangeevents because they fire on every keystroke and produce annoying pop-ups. - 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_Clickstub. - 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 - Validate numbers with
IsNumeric. A text box accepts anything, so test before converting.If Not IsNumeric(txtAge.Value) Thencatches letters and symbols. Then check the range:If Val(txtAge.Value) < 18 Or Val(txtAge.Value) > 120 Then. Always useValorCDblonly afterIsNumericpasses, otherwise you get a type mismatch error. - Validate dates with
IsDate. UseIf Not IsDate(txtStart.Value) Thenand then compare withCDate(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. - Check combo box and list box selections. A combo box with no selection has
ListIndex = -1. A list box can have multiple selections; loop throughListCountand testSelected(i)if you need at least one item chosen. - Validate option buttons and check boxes. For a group of option buttons, test each one's
Value. If none isTrue, show a message. For check boxes that require consent, testIf Not chkAgree.Value Then. - Use
Cancel = Trueto keep the form open. InsidecmdOK_Click, settingCancel = Trueprevents the form from closing. This is the cleanest way to stop the close after a failed check. You can combine it withExit Subfor clarity. - Highlight the offending control. After showing the message, call
SetFocuson the control so the cursor lands there. Optionally change itsBackColorto a light red and reset it on the next valid entry. Keep the color change simple; too much color switching looks noisy. - 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.
- 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
Changeevent. 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, sotxtName.Value = ""misses a field containing only spaces. - Using
ValbeforeIsNumeric.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 aQueryClosecheck 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 Booleanto keep the OK handler short. - Set
MaxLengthon text boxes where a length limit applies; it prevents the error instead of reporting it. - Use
Tagproperty 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
Showmethod 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.