SetFocus

M

MikeS

I have a form in which a Model Number and Serial Number gets scanned into
their respective fields. I am trying to validate these numbers so they don't
get crossed. Serial Numbers always begin with the letters "TH". So here is
my code:

Private Sub Model_AfterUpdate()
On Error GoTo Err_Model_AfterUpdate

If Left(Me.Model.Value, 2) = "TH" Then
Me.Model.Value = ""
MsgBox "Invalid Model Number! ", vbOKOnly
Me.Model.SetFocus
End If

Exit_Model_AfterUpdate:
Exit Sub

Err_Model_AfterUpdate:
MsgBox Err.Description
Resume Exit_Model_AfterUpdate

End Sub

The problem is the focus will not go back to the "Model" field.

Can anyone tell me why?

Thanks in advance,
MikeS
 
D

David H

Try switching to the _BeforeUpdate event of the control. Usually works out
better with validation.
 
K

Klatuu

Setting focus to yourself doesn't really work. You would be better off to
use the Before Update event of the control. That way, you can cancel the
update of the control and the cursor will remain in the control:

Private Sub Model_BeforeUpdate(Cancel As Integer)
On Error GoTo Err_Model_BeforeUpdate

If Left(Me.Model.Value, 2) = "TH" Then
MsgBox "Invalid Model Number! ", vbOKOnly
Cancel = True
End If

Exit_Model_BeforeUpdate:
Exit Sub

Err_Model_BeforeUpdate:
MsgBox Err.Description
Goto Exit_Model_BeforeUpdate

End Sub
 
D

David H

Cancel = True cancels the triggering event. Try explicity clearing the field

Me.FieldName.Value = ""

Also, if its a situation where the two values can be switched you may want
to add code that does that automatically and then present a dialog box for
the user to confirm the values.
 
K

Klatuu

Me.FieldName.Undo

is a better choice. There may be a value in the control you don't want to
remove.
 
J

JonWayn

Private Sub Model_BeforeUpdate(Cancel As Integer)
Cancel = Model Like "TH*"
If Cancel Then MsgBox "Invalid Model Number. Must be prefixed with 'TH'"
End Sub
 

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

Similar Threads


Top