Working with Error Events
Every form and report contains an error event procedure. This event is triggered by any interface or Jet Database Engine error. It is not triggered by a programming error made by the Access developer.Errors often occur in the interface of a form or report, as well as in the Jet Database Engine. A user might try to enter an order for a customer who doesn't exist, for example. Instead of displaying Access's default error message, you might want to intercept and handle the error in a particular way.After an error occurs within a form, its error event is triggered. In Listing 16.36, you can see Sub Form_Error. It contains two parameters. The first parameter is the number of the error. The second is the way you want to respond to the error. The error number is an Access-generated number.This code, which is located in the frmOrders form in the CHAP16EX.MDB database, tests to see whether a referential integrity error has occurred. If it has, a message box asks whether the user wants to add the customer. If the user answers Yes, the customer form is displayed.
Listing 16.36 Viewing Sub Form_Error From the Form frmOrders
Private Sub Form_Error(DataErr As Integer, Response As Integer)
Dim intAnswer As Integer
If DataErr = 3201 Then 'Referential Integrity Error
intAnswer = MsgBox("Customer Does Not Exist... _
Would You Like to Add Them Now?", vbYesNo)
If intAnswer = vbYes Then
DoCmd.OpenForm "frmCustomer", , , , acAdd, acDialog
End If
End If
Response = acDataErrContinue
End Sub
CAUTIONBe aware that the code in Listing 16.36 only traps referential integrity errors. It does not handle any other error.The Response = acDataErrContinue line is very important. It instructs Access to continue the code execution without displaying the standard error message. The other option for Response is AcDataErrDisplay. It tells Access to display the default error message.