Microsoft Access VBA Macro Programming

(Tina Sui) #1

Chapter 8 Errors and the Error Function


Chapter 8 Errors and the Error Function


R


untime errors can creep into code very easily, through no fault of the programmer.
The user does something outside the scope of the code and causes an error
message to occur that stops all execution of code. This may occur when you are
accessing an external data source such as a database. The user may also take an action that
the programmer never envisaged.
No matter how carefully you try to provide for all conditions, there is always a user who
does something you never thought of and effectively breaks the set of rules you wrote. It may
be as simple as including a name with an apostrophe, such as O’Brien. If you use this name
in a SQL query string, it will cause problems in the way it is handled.
Another example is reading a file in from a disk device. The programmer may allow the
user to select the drive letter for the file to be read. You assume that the files will mainly
come from network drives, and a D: CD/DVD option is just nice to have, but it will probably
never be used. However, if the user selects D: (CD/DVD drive), it is possible there will be no
disk in the drive. This will create an error that will stop execution of your program. The user
will then be very unhappy and lose a great deal of faith in your application. Thus, the error
needs to be trapped, and an appropriate action needs to be taken from within the VBA code.
Error handling is also used on common dialog forms (see Chapter 10) to show that the
Cancel button has been clicked. In order to test whether the user clicked the Cancel button,
you must have first set theCancelErrorproperty to True and then put in anOn Error
statement to direct the code where to go for an error.


91

Free download pdf