SetFocus Thing

  • Thread starter Thread starter John
  • Start date Start date
J

John

The following code is supposed to check if something was
entered in the Social Security textbox. If the box was
left empty, the user is supposed to get an error message
(this part works) when he attempts to go to the next
control and, after he clicks OK on the message box, the
focus should be set back on the Social Security textbox.
For some reason the Social Security box does not receive
the focus. Can you help?

Private Sub txtSSN_LostFocus()
txtSSN.SetFocus
If Len(txtSSN.Text) = 0 Then
MsgBox "You must enter the client's Social Security Number
(SSN)!", vbExclamation, "Insufficient Data"
txtSSN.SetFocus
End If
End Sub
 
Setting Focus back to the same control won't work. The event fires before
the focus has moved to the next control, so it runs your code (setting focus
to the control that still has focus), and then moves on to the next control.

To validate a field, you would normally use its BeforeUpdate event.
Cancelling that event leaves focus in the control. This event doesn't fire
unless something is entered into the control.

You have no guarantee that the user will ever enter the contorl anyway. They
may click in a later control and never visit txtSSN.


To guarantee that the record cannot be saved if the field is blank:
1. Open the table in design view.
2. Select the SSN field.
3. In the lower pane, set the Required property to Yes.


If you want to warn the user but allow them to override this, use the
BeforeUpdate event procedure of the form:

Private Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
If IsNull(Me.txtSSN) Then
strMsg = "SSN is blank. Continue anyway?"
If MsgBox(strMsg, vbYesNo+vbDefaultButton2) <> vbYes Then
Cancel = True
End If
End If
End Sub
 
Back
Top