control cannot lose focus if conditions are not met

R

randria

hi,
I have a control on a subform that has conditions and if they are not met an
error message pops up ( on lost focus ). Now I realised that the users might
ignore the error and continue. What I would like to happen is either:
-The user cannot move out from that control until the value is corrected
or
-a code sets the value to meet the condition on lost focus.

my codes
Private Sub N0Unit_LostFocus()
If Me.N0unit = 0 And (Me.Service = 5 Or Me.Service = 9 Or Me.Service = 12)
Then
MsgBox (" N0Unit can't be 0.")

Else
If Me.N0unit <> 0 And Not (Me.Service = 5 Or Me.Service = 9 Or Me.Service
= 12) Then
MsgBox (" Please set the value of N0Unit to 0")
Else

End If
End If
End Sub

Your help is appreciated.
 
B

BruceM

Try the control's Before Update event instead. It can be canceled:

Private Sub N0Unit_BeforeUpdate(Cancel As Integer)

If Me.N0unit = 0 And (Me.Service = 5 Or Me.Service = 9 Or Me.Service = 12)
Then
MsgBox (" N0Unit can't be 0.")
Cancel = True
Else
MsgBox (" Please set the value of N0Unit to 0")
Cancel = True
End If

End Sub

Or maybe:

If Me.N0unit = 0 And (Me.Service = 5 Or Me.Service = 9 Or Me.Service = 12)
Then
MsgBox "N0Unit can't be 0"
Me.txtN0Unit.SetFocus
Cancel = True
Else
If Me.N0Unit <> 0 Then
Me.NoUnit = 0
MsgBox "N0Unit has been reset to 0"
End If
End If

Note that you do not have to repeat the logical test. If the first
condition is not met the only option for N0Unit is 0.

I assume there are several options for N0Unit when Me.Service is 5, 9, or
12. Is that correct?
 
B

BruceM

I realized just as I sent my reply that there is a need to set the focus to
the control, as canceling the update will have the same effect. However,
you will probably want to undo what has been typed:

If Me.N0unit = 0 And (Me.Service = 5 Or Me.Service = 9 Or Me.Service = 12)
Then
MsgBox "N0Unit can't be 0"
Me.txtN0Unit.Undo
Cancel = True
Else
If Me.N0Unit <> 0 Then
Me.NoUnit = 0
MsgBox "N0Unit has been reset to 0"
End If
End If

Note that Then is the end of the line starting with If Me.N0Unit. Word
wrapping in your newsreader may alter this.
 

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