As DatabaseMX suggests Form_Error event will trap errors which you can respond, but using it isn't as straight forward as it looks.
Let's say you create Table1 with 5 fields. Field1 and Field2 are required fields Next you create a form where Fields 1, 2 etc. are bound to TextBox1, TextBox2 etc.
If you enter something in text boxes 3 -5, but don't enter values in TextBox1 or TextBox2 when you attempt to update the record e.g when you select another record you'll get an error. The error message will be "You must enter a value in Table1.Field1" or "You must enter a value in Table1.Field1" . So far so familiar.
The problem is that the Form_Error event will pass the same error number (3314) when TextBox1 has, a value but TextBox2 doesn't or vice versa. So how do you let the user know which text box needs to be filled in?
Well you could make it conditional e.g
Select Case DataErr
Case 3314
If IsNull(TextBox1) Then
MsgBox "TextBox1 needs a value"
Else
MsgBox "TextBox1 needs a value"
End If
Case ,,,,
- Code
Case Else
Other Code
End Select
So far, so good, but lets add another manditory condition like Field1<=Field2. You can't create a validation rule like this in an Access table so you'd have to validate this elsewhere. As you can see the more complex your validation becomes, the less easy it is to use the Form_Error event to do everything.
When you have complex validation you can by pass access raising data error events by validating the record using a validation function like this in Form_BeforeUpdate event
Private Function IsValidRecord() As Boolean
On Error GoTo Err_IsValidRecord
Dim strError As String
Dim strControl As String
'Validation.
If IsNumeric(TextBox1) And IsNumeric(TextBox2) Then
If TextBox1 > TextBox2 Then
strError = "TextBox1 should be less than or equal to TextBox2"
strControl = "TextBox1"
GoTo Error_Message_Handler
End If
Else
strError = "TextBox1 should be less than or equal to TextBox2"
strControl = "TextBox1"
GoTo Error_Message_Handler
End If
'---------
'Other validation code
'----------
Error_Message_Handler:
If strError = "" Then
IsValidRecord = True
Else
MsgBox strError
Me.Controls(strControl).SetFocus
End If
Exit_IsValidRecord:
Exit Function
Err_IsValidRecord:
MsgBox "IsValidRecord Error: " & Err.Number & ": " & Err.Description
Resume Exit_IsValidRecord
End Function
The Form_BeforeUpdate event fires before Form_Error event, so the following will force the user to create a valid record or bail out by clicking on an undo button
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Not IsValidRecord Then Cancel = -1
End Sub