SetFocus Problem

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

Guest

Hi all,

Can someone tell me why the following code isn’t working correctly?

I have a TimeDepart and a TimeReturn controls. When someone enters a
TimeReturn before the TimeDepart it generates a message and clears out the
TimeReturn then the focus is returned to the TimeReturn.

Everything works fine except setting the focus back on TimeReturn. The focus
goes to the Coordinator control. The Coordinator control is next in the Tab
Order. I’ve tried moving different controls in the Tab Order and whatever
control is after TimeReturn it sets the focus there. Basically the Tab Order
is taking control over the code.

I’m having the same type of problem with another database. I’ve used the
SetFocus like this before and until recently have not had any problems.

Private Sub TimeReturn_AfterUpdate()

If TimeReturn < TimeDepart Then
MsgBox "You entered an improper time. You can't return before you leave.
Enter another return time."
TimeReturn.SetFocus
TimeReturn = ""

Else

Coordinator.SetFocus

End If

End Sub

Thanks for the help,

Paul
 
It's a timing problem.

The code runs before focus has left TimeReturn.
Consequently the TimeReturn.SetFocus does nothing.
Then after the code completes, the focus moves on as normal.

To avoid the problem, use the BeforeUpdate event of the control, and cancel
the event:

Private Sub TimeReturn_BeforeUpdate(Cancel As Integer)
If TimeReturn < TimeDepart Then
MsgBox "You entered an improper time..."
Cancel = True
End If
End Sub
 
You cannot cancel a focus move in the AfterUpdate event. Thus, if the user
tabbed from the TimeReturn control, your code will run but the focus will
continue to go to the next control in the tab order.

Use the BeforeUpdate event instead and cancel it if the user's entry is
invalid:

Private Sub TimeReturn_BeforeUpdate(Cancel As Integer)
If TimeReturn < TimeDepart Then
MsgBox "You entered an improper time. You can't return before you leave.
Enter another return time."
Cancel = True
TimeReturn.Undo
End If
End Sub


Or you can use the Exit event of the control:


Private Sub TimeReturn_Exit(Cancel As Integer)
If TimeReturn < TimeDepart Then
MsgBox "You entered an improper time. You can't return before you leave.
Enter another return time."
Cancel = True
TimeReturn = ""
End If
End Sub
 
Back
Top