Originally Posted by
Robeen
...
put some code in the GotFocus event of the second field of your Form - something like this:
Code:
Private Sub ControlName2_GotFocus()
Me.ControlName1.SetFocus
If Me.ControlName1.Text = "" Then
MsgBox "Please enter a value in the Text box."
Me.ControlName1.SetFocus
End If
End Sub
What I sometimes do, is to put the Code in the 'Save' or 'Submit' button of the Form and then check all the fields to make sure they have legitimate values . . .
There are several things wrong with this answer/approach!
- If the object here is to make sure that the first Control is populated, what happens if they skip the first Control...and the second Control?
- The test If Me.ControlName1.Text = "" will fail about 999 times out of 1000! This is only testing for a Zero-Length String (ZLS), it does not test for a Null, which is what an 'empty' Control usually contains!
- Also, you cannot refer to the .Text Property of a Control, unless the Control has Focus; in this circumstance you have to use the .Value Property!
- Putting this kind of code in a 'Save' or 'Submit' button, both of which are unnecessary, in an Access Database, will not keep the Record from being saved, even if the Field is empty, because a Command Button does not have a Cancel event that can be used to Cancel the update if the data is missing or invalid. Validation to assure that a Field is populated has to be in the Form_BeforeUpdate event, which does have a Cancel event, so that saving the Record can be put on hold until the omission is corrected.
The problem mentioned in #2 and #3, above, can be corrected in a couple of ways, all of which test for both Null and ZLS. Here's one:
If Nz(Me.ControlName1.Value, "") = "" Then
Now, before giving a definitive answer your question, we need to know if your sole purpose is to insure that the first Control has data before the Record is saved, or if it does, in fact, have to be populated before data is entered into the second Control. And if the latter is true, do both of these Controls have to be populated before saving the Record?
Linq ;0)>
The problem with making anything foolproof...is that fools are so darn ingenious!
All posts/responses based on Access 2003/2007