Microsoft Office VBA: Keep Focus on an Invalid UserForm TextBox
Question details
Keep the user's focus in a UserForm TextBox when its value fails VBA validation.

- Product
- Microsoft Office VBA UserForms
- Device & OS
- not provided
- Scenario
- A VBA UserForm validates a TextBox value as the user moves to another control.
- Observed behavior
- After validation rejects the value, focus may move to the next control instead of staying in the invalid TextBox.
Open the Office file containing the UserForm and identify the TextBox and its validation rule. In the VBA editor, check whether validation already runs in an event that may conflict with the TextBox Exit event.
Cancel the TextBox Exit event when validation fails
Use the Exit event to prevent focus from leaving the TextBox until the user corrects an invalid value.
Open the Visual Basic editor, locate the UserForm in Project Explorer, and open its code window.
In the code window, select the TextBox from the object list and Exit from the event list.
In the generated Exit procedure, set Cancel to True when the value is invalid. For example, replace TextBox1 with your control's name and use: Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean) If Len(Trim$(Me.TextBox1.Value)) = 0 Then MsgBox "Enter a value before continuing." Cancel = True End If End Sub
Run the UserForm, leave the TextBox empty, and press Tab or click another control. After dismissing the message, enter a valid value and try moving on again.

Check whether the UserForm is shown modally
Review the form's modal setting if focus behavior remains inconsistent, especially when the form is currently modeless.
Work with Office spreadsheets in WPS Office
WPS Office is a free, lightweight alternative with a familiar interface for working with Office files. Open compatible spreadsheets and migrate everyday editing tasks with ease; it does not fix Microsoft Office VBA UserForm focus behavior.

Frequently Asked Questions
Why does focus move to the next control after validation fails?
Displaying an error message alone does not cancel a focus change. In the TextBox Exit event, set Cancel = True when the value is invalid.
Does Cancel = True select the invalid text?
No. It prevents the TextBox from losing focus, but it does not automatically select its contents.
Where can I find the TextBox Exit event?
Open the UserForm's code window in the Visual Basic editor, select the TextBox from the object list, and then select Exit from the event list.
Can a modeless UserForm affect focus behavior?
It can contribute to inconsistent focus behavior. Check the UserForm's ShowModal property and the code calling Show; an explicit vbModeless argument displays the form modelessly even if ShowModal is True.




