Reputation: 827
I have an Excel userform with textboxes to put various information (first name, last name, gender, height, etc.). For some of the textboxes, I want to apply a sort of validation.
For the gender field, for example, the only values that are acceptable are "M" or "F." I have this bit of code. If you type "M" or "F" and tab out of the field, it goes to the next textbox. But if it's anything else, the MsgBox will pop up like it should, but after you click OK, the focus is not set to the textbox.
What am I doing wrong? Shouldn't this work?
Private Sub txtGender_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If txtGender.Value <> "M" And txtGender.Value <> "F" Then
MsgBox ("Invalid gender.")
txtGender.SetFocus
End If
End Sub
Upvotes: 0
Views: 2618
Reputation: 374
You can cancel the Exit
event within your If
statement.
Private Sub txtGender_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If txtGender.Value <> "M" And txtGender.Value <> "F" Then
MsgBox ("Invalid gender.")
Cancel = True
End If
End Sub
Upvotes: 1