Setfocus not working in form?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a user form that I am providing an error message if the enter an
incorrect date. I want to then set the focus back to the date field after
the error. I am using the below code to do this however it is not setting
the focus back to the date field? Am I doing something wrong or is their a
property on the fields that overrides the "setfocus"?

Any help would be greatly appreciated.

Private Sub DateRec_Exit(Cancel As Integer)

If DateDiff("d", DateRec, Now) > 30 Or DateDiff("d", DateRec, Now) <
0 Then
MsgBox "Date is either in the future or entered in an incorrect
year. Please re-enter"
Me.DateRec.SetFocus

End If
End Sub
 
Kathy said:
I have a user form that I am providing an error message if the enter
an incorrect date. I want to then set the focus back to the date
field after the error. I am using the below code to do this however
it is not setting the focus back to the date field? Am I doing
something wrong or is their a property on the fields that overrides
the "setfocus"?

Any help would be greatly appreciated.

Private Sub DateRec_Exit(Cancel As Integer)

If DateDiff("d", DateRec, Now) > 30 Or DateDiff("d", DateRec,
Now) < 0 Then
MsgBox "Date is either in the future or entered in an
incorrect year. Please re-enter"
Me.DateRec.SetFocus

End If
End Sub

For validation like this the best event to use is BeforeUpdate of the
control and then set the Cancel argument to True if the validation fails.
This way the control never loses focus thus there is no requirement to set
it back.
 
I must be missing something because it is still not working for me. I have
moved my code (shown below) to the Before Update Event. However, after
clicking Ok on the msgbox, the focus is taken to the next field on my form.
I want the focus to be placed back on my date field.

Any suggestions?

Private Sub DateRec_BeforeUpdate(Cancel As Integer)
If DateDiff("d", DateRec, Now) > 30 Or DateDiff("d", DateRec, Now) < 0
Then
MsgBox "Date is either in the future or entered in an incorrect
year. Please re-enter"

End If
End Sub
 
Where are you doing the "Cancel = True"?


Kathy - Lovullo said:
I must be missing something because it is still not working for me. I have
moved my code (shown below) to the Before Update Event. However, after
clicking Ok on the msgbox, the focus is taken to the next field on my
form.
I want the focus to be placed back on my date field.

Any suggestions?

Private Sub DateRec_BeforeUpdate(Cancel As Integer)
If DateDiff("d", DateRec, Now) > 30 Or DateDiff("d", DateRec, Now) < 0
Then
MsgBox "Date is either in the future or entered in an incorrect
year. Please re-enter"

End If
End Sub
 
Use the BeforeUpdate Event instead where you can cancel the Event (by
setting the Cancel argument to True)and retain the Focus on the Control.

The Exit Event is too late as the Control which will received the Focus has
already been decided.
 
Back
Top