Handling Errors in Code

We discussed the various types of errors in Chapter 9, but we have scrupulously avoided the question of how to handle run-time errors in code. Indeed, VBA provides several tools for handling errors (On Error, Resume, the Err object, and so on), and we could include an entire chapter on the subject in this book.

Proper error handling is extremely important. Indeed, if you are, or intend to become, a professional application developer, then you should familiarize yourself with error handling procedures.

On the other hand, if your intention is to produce Access VBA code for your own personal use, then the reasons for adding error handling routines are somewhat mitigated. For when an error occurs within one of your own programs, VBA will stop execution, display an error message, and highlight the offending code. This should enable you to debug the application and fix the problem. (It would be unreasonable to expect another user of your program to debug your code, however.)

Let us undertake a brief discussion of the highlights of error handling. (For more details, may I suggest my book Concepts of Object-Oriented Programming in Visual Basic, published by Springer-Verlag. It has a detailed chapter on error handling.)

The On Error Goto Label Statement

The On Error statement tells VBA what to do when a run-time error occurs. The most common form of the statement is:

On Error GoTo label

where label is a label. For instance, consider the following code:

Sub RecordCt() ...

Get Access Database Design and Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.