ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Data validation in Userform sub (https://www.excelbanter.com/excel-programming/432008-data-validation-userform-sub.html)

Marcolino

Data validation in Userform sub
 
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.

Jacob Skaria

Data validation in Userform sub
 
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
---------------
Jacob Skaria


"Marcolino" wrote:

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.



All times are GMT +1. The time now is 01:46 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com