Validating text box values

  • Thread starter Thread starter Tony Nichols
  • Start date Start date
T

Tony Nichols

I am having a problem setting focus back to the text box I
am trying to validate.

I have a validation routine running in the lost focus
event as listed below for a text box "txtTest".

Private Sub txtTest_LostFocus()
Dim sTest As String
Dim sMsg As String
sTest = txtTest.Value


If Not IsNumeric(sTest) Then
sMsg = "Must be numeric"
MsgBox sMsg, vbOKOnly
txtTest.Value = ""
txtTest.SetFocus
Exit Sub
End If
End Sub

But the focus does not set back to the txtTest control, it
follows the keyboard stroke of enter or mouse click into
the next control on the tab order index.

This seems like it should be so easy to do but it is
not. I am not using the validaterule property because I
want to build a second test into the procedure an pass a
different error message to the user based on a range
value.

I am really feeling stupid on this one. Can anyone shed
some light.

Thanks in advance,
Tony Nichols
 
Tony said:
I am having a problem setting focus back to the text box I
am trying to validate.

I have a validation routine running in the lost focus
event as listed below for a text box "txtTest".

Private Sub txtTest_LostFocus()
Dim sTest As String
Dim sMsg As String
sTest = txtTest.Value


If Not IsNumeric(sTest) Then
sMsg = "Must be numeric"
MsgBox sMsg, vbOKOnly
txtTest.Value = ""
txtTest.SetFocus
Exit Sub
End If
End Sub

But the focus does not set back to the txtTest control, it
follows the keyboard stroke of enter or mouse click into
the next control on the tab order index.

This seems like it should be so easy to do but it is
not. I am not using the validaterule property because I
want to build a second test into the procedure an pass a
different error message to the user based on a range
value.


Data validatation is better done in the text box's
BeforeUpdate event. This event provides a Cancel argument
that can be set to True to prevent the update from proceding
and the control will not lose the focus


Private Sub txtTest_BeforUpdate(Cancel As Integer)
Dim sMsg As String

If Not IsNumeric(txtTest.Value) Then
sMsg = "Must be numeric"
MsgBox sMsg, vbOKOnly
txtTest.Value = NULL
Cancel = True
End If
End Sub
 
Back
Top