Setting focus back on a field

G

Guest

OK, I have a field that I am checking the value that is entered. If the
value does not match the criteria then I pops up a msgbox and telss the user
that it is wrong. I am using the afterupdate event for this. What i Can't
get to happen is to set the focus back on that field so they have to enter a
correct value before moving on.

Hre is my code

Private Sub Debit_AfterUpdate()
If Me.Debit > 0 Then
MsgBox "This field requires a negative amount.", vbOKOnly, "Wrong value"
Debit.SetFocus

End If

Net = Debit

End Sub
 
F

fredg

OK, I have a field that I am checking the value that is entered. If the
value does not match the criteria then I pops up a msgbox and telss the user
that it is wrong. I am using the afterupdate event for this. What i Can't
get to happen is to set the focus back on that field so they have to enter a
correct value before moving on.

Hre is my code

Private Sub Debit_AfterUpdate()
If Me.Debit > 0 Then
MsgBox "This field requires a negative amount.", vbOKOnly, "Wrong value"
Debit.SetFocus

End If

Net = Debit

End Sub

You're using the wrong event.
Use the control's BeforeUpdate event.
Set Cancel = true.

Private Sub Debit_BeforeUpdate(Cancel as Integer)
If Me.Debit > 0 Then
MsgBox "This field requires a negative amount.", vbOKOnly, "Wrong
value"
Cancel = True
End If
 
G

Guest

To answer your question, you can't set focus to a control that has the focus,
but that is not your problem. The real issue here is your code is in the
wrong event. it should be either in the Control's Before Update or the
Form's Before Update event.
It would be better in the Form's Before Update, because if you put it in the
Control's Before Update event, it is difficult to get out of the control if
you want to. The difference is that Before Update events can be canceled
where After Update events cannot.

Private Sub Form_BeforeUpdate(Cancel As Integer)

If Me.Debit > 0 Then
MsgBox "This field requires a negative amount.", vbOKOnly, "Wrong
value"
Cancel = True
Me.Debit.SetFocus
End If

Also, I notice you are checking for > 0, but you say it is a negative anount
that is required. If 0 is okay, then you logic is correct; otherwise, it
should be >=0
 
G

Guest

I personnally use the Exit event.

Private Sub Debit_Exit(Cancel As Integer)
If Me.Debit > 0 Then
MsgBox "This field requires a negative amount.", vbOKOnly, "Wrong value"
Cancel = False

End If

Net = Debit

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

Top