Error Catching On Access VBA
To use error detection on Access you need to use the command On Error GoTo and then give the error label a name. When the code comes across an error it will run the code in the error handling section. The following code will try to open a form that doesn’t exist, when an error occurs the code will print out "Can’t Find Form" to the Immediate window and then exit.
Sub run()
On Error GoTo ErrHandler
DoCmd.OpenForm "aNonExistantForm", acNormal, , , acFormEdit, acWindowNormal
Exit Sub
ErrHandler:
' error handling stuff
Debug.Print "Can't Find Form"
Exit Sub
End Sub
The name of the error section must be the same as the name you entered when you set up the error section with On Error GoTo. Don’t forget the colon as well as this turns it into a label.
Whilst in the error section the Err object is available to use. This will give you any information about the error that is available to the system. So to get more details information about the error you can print off the description by using the variable Err.Description. From the above example this would print off the text The form name 'aNonExistantForm' is misspelled or refers to a form that doesn’t exist. to the Immediate window.
Of course you might want to do more to the code than just exit. You could use a global function that will send an email or otherwise log the error so you can deal with the issue later. It is always best to deal with errors in a positive way when they happen.
Write a comment