Hello,
I have two text boxes, one called "MobileNumber" and the other called "Requests".
What command should I type in "Before Update" Event to prevent the Access from saving the record until they are filled together?
If Len(Me.MobileNumber & Requests) = 0 Then
MsgBox "You need to fill out SomeControl"
Cancel = True
Me.MobileNumber.SetFocus
End If
Then After opening the form and trying to save it without filling the text box, I get the following message
Microsoft Access cannot find the object if Len(Me.'
if 'if Len(Me' is a new macro group, make sure you have saved it and that you have typed its name correctly
I modified it and put it before update, but the same message appeared ,,
Frankly, I don't know how to use the code. Should I create a macro first for this code and then put it in before update or what?
Sorry guys, it was my mistake.
I was trying to write the code from the Zoom interface ,
But when i research on this topic, I noticed that the code had to be written using Code Builder...
Thank you so much, @pbaldy you are a lifesaver, and thank you @jdraw for participating..
Just FYI, the BeforeUpdate event is attached to both controls and the form. When you are creating validation code that involves more than a single field, then you need to use the FORM's BeforeUpdate event rather than writing the code TWICE and using the control events. Also, unless a control is actually modified, the control's BeforeUpdate event will NOT fire. Therefore, you can NEVER use the control level events to determine if a value has been entered, you need to use the FORM's BeforeUpdate event.
Code:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = True ''set Cancel = true until all validation is complete
If Me.MobileNumber & "" = "" Then
MsgBox "Mobile Number is required.", vbOKOnly
Me.MobileNumber.SetFocus
Exit Sub
End If
If Me.Requests & "" = "" Then
Msgbox "Requests is required.", vbOKOnly
Me.Requests.SetFocus
Exit Sub
end If
Cancel = False ''set Cancel = False when no errors are found
End Sub
Rarely do data entry people make multiple errors when entering data. Therefore, the simplest method is to validate them independently and exit the BeforeUpdate event after each error is found. The Cancel = True will leave the record dirty but prevent Access from saving it. This allows me to easily highlight the control with the error.
When rules are dependent on each other, they are coded as nested If's or sometimes GoSub's if the rule is complicated and easier to view out of the mainline.