Validation Woes....

N

NotGood@All

All I want for this week is to understand why this code does not work. I
have a text field named "EmpFirstName", when I leave this field, if for any
reason the field is blank I would like to see a msgbox. I get an error when
I use the "Cancel" code, but when I don't I can just tab to the next field.

Private Sub EmpFirstName_AfterUpdate()
If Me.EmpFirstName.Text = vbNullString Then
MsgBox "Value required", vbOKOnly, "First Name Missing!!"
'Cancel
Me.EmpFirstName.SetFocus
End If
End Sub

Thanks In Advance
 
J

Jeanette Cunningham

Try this in the Before Update event for the control

Private Sub EmpFirstName_BeforeUpdate()
If Me.EmpFirstName.Text = vbNullString Then
MsgBox "Value required", vbOKOnly, "First Name Missing!!"
Cancel = True
End If
End Sub

Jeanette Cunningham
 
A

Allen Browne

Suggestions:

1. Test the Value rather than the Text

2. Test for Null, rather than zero-length string.

3. Use the control's BeforeUpdate if you want to cancel the event.

4. If you want to check that the first name was entered before the record
gets saved -- even if the user never visited the control -- use the
BeforeUpdate event of the *form*, not the control.

5. If you want to prevent the record being saved if the first name was not
entered, you don't need any code. Just open the table in design view, and
set the field's Required property to Yes.

Here's an example of how you would check if a field was left blank, but
allow the user to override it (#4 above):

Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim strMsg As String
If IsNull(Me.EmpFirstName) Then
strMsg = "No first name. Save anyway?"
If MsgBox(strMsg, vbYesNo+vbDefaultButton2, "Really?") <> vbYes Then
Cancel = True
'Me.Undo
End Sub
End If
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