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 labelwhere
label
is a label. For instance, consider the following code:
Sub RecordCt() ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access