Data validation in Userform sub

M

Marcolino

If a user enters the wrong info into a textbox control, how do I program the
userform to display an error message and return the user to the textbox to
enter the correct info?

I've tried using the Exit event with a MsgBox inside a Do While...Loop, but
either the MsgBox keeps looping, or the focus switches to the next control,
even if I use the SetFocus method:

Private Sub ControlNumb_Exit(ByVal Cancel As MSForms.ReturnBoolean)

Do While IsNumeric(NewResEntryForm.ControlNumb.Value) = False _
Or Len(NewResEntryForm.ControlNumb.Value) <> 5

response = MsgBox("Please enter a valid control number", vbOKOnly)

If response = vbOK Then
NewResEntryForm.ControlNumb.SetFocus
Exit Sub
End If

Loop

End Sub

Please help, thanks.
 
J

Jacob Skaria

Try the below.

Private Sub ControlNumb_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If IsNumeric(Me.ControlNumb) = False Or Len(Me.ControlNumb) <> 5 Then
MsgBox "Please enter a valid control number", vbOKOnly
Cancel = True
End If
End Sub

If this post helps click Yes
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top