First off, Validation code to determine if a Control has been left empty (Null) simply has to be placed in the Form_BeforeUpdate event! Notice that I said the BeforeUpdate event of the Form, itself, not one associated with a Control.
When checking Controls for Nulls, tying code to events associated with those Controls is useless! All a user has to do, to get around the code, is to simply not enter the Control in the first place; the Validation code wouldn't fire! Placing the Validation code in the Form_BeforeUpdate does three things:
- It eliminates the problem I just spoke about
- It allows the update of the Record to be prevented (aka canceled) until the deficit is corrected
- It eliminates the problem you have, with the LostFocus code firing before and interfering with the exit code.
Here's some sample code of this type of thing; the example checks two Controls, but it can be modified to validate any number of Controls:
Code:
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Nz(Me.Control1,"") = "" Then
MsgBox "Control1 Must Not Be Left Blank!"
Cancel = True
Control1.SetFocus
Exit Sub
End If
If Nz(Me.Control2, "") = "" Then
MsgBox "Control2 Must Not Be Left Blank!"
Cancel = True
Control2.SetFocus
Exit Sub
End If
End Sub
I'm a little fuzzy as to your exit strategy, here. If you want the user to be able to exit the Form and not save the incomplete Record, i.e the Record that has required Fields that are empty, you need to add this line just prior to your code that closes the Form:
Me.Undo
Linq ;0)>
The problem with making anything foolproof...is that fools are so darn ingenious!
All posts/responses based on Access 2003/2007