Access VBA Macro Programming

(Joao Candeias) #1
If there is no disk in drive D, the code will still run perfectly because ofOn Error Resume
Next—it skips over the line of code creating the error.
Resume Nextcan be useful for dealing with errors as they occur, but it can make debugging
code very difficult. In a later stage of your program, you may have incorrect or nonexistent data
being produced due to the fact that an error condition earlier was ignored. You can end up with
a program that appears to run okay, but in fact does nothing because it has some hidden bugs or
incomplete data. This is because every time an error is encountered, the execution just skips
over it. This can give a false impression of what is actually happening, so if you do useOn
Error Resume Next, make sure you check all inputs and outputs to the code to ensure that
everything is working as it should. Make sure yourOn Error Resume Nextstatement cannot
cover up an error in a read from a table or from a file. This can be disastrous for your program
because theOn Error Resume Nextstatement will make it appear to work perfectly.

Implications of Error Trapping


When you use anOn Errorstatement in your code, that error trap remains throughout the
procedure unless it is disabled. As you just saw, you can set up a routine to check whether the D
drive has a disk in it and take action accordingly. However, it is important to turn this off once the
possibility of the error has taken place. If you do not do this, then all subsequent errors within that
procedure will use the same error-handling routine. This gives extremely confusing results to the
user, as the error message is likely to be totally meaningless in relation to the error generated.
A subsequent error could relate to division by zero, but the error message will come up saying
“Drive D not ready.”
IfOn Error Resume Nexthas been used and not switched off, all sorts of errors could be
taking place without the user being aware of them. You disable the error-trapping routine as
follows:

On Error Resume Next
On Error GoTo 0

TheOn Error Resume Nextstatement that you saw previously ignores all errors. TheOn Error
GoTo 0cancels any error handling and allows all errors to be displayed as they normally would.
This cancels out theOn Error Resume Nextand puts everything back to normal error handling.

Generating Your Own Errors


Why would you want to generate your own errors? After all, you want to achieve error-free
code, right? Well, sometimes this is useful when you are testing your own applications or
when you want to treat a particular condition as being equivalent to a runtime error.

94 Microsoft Access 2010 VBA Macro Programming

Free download pdf