Learn Access 2003 VBA with The Smart Method
104
www.LearnAccessVBA.com
Lesson 5-8: Implement error
handling
The code that has been written so far has no error handling. This means
that when something goes wrong the program “crashes" causing the
default error handler to display.
Professional code always includes custom error handling in every sub
and function (see sidebar) so that you are in control when something
goes wrong. We’re now going to add error handling to bring the code to
a level that a professional programmer would be proud of.
1
If it is not already open, open the VBACode.mdb
spreadsheet and open frmTest in Design View.
2
Enter some text into one of the text boxes instead of a
number and then click the Add Two Numbers command
button.
A run-time error dialog appears.
The error appears because Error Handling has not been
implemented resulting in the program code crashing.
3
Click the End button, Open the VBA Editor and navigate to
the cmdAddTwoNumbers command button’s Click event
handler.
4
Add error handling code to the cmdAddTwoNumbers
command button’s Click event handler.
Modify the code as follows (new error handling code is shown
boldfaced):
Private Sub cmdAddTwoNumbers_Click()
On Error GoTo ErrorHandler
Dim dblFirstNumber As Double
Dim dblSecondNumber As Double
Dim dblSumOfNumbers As Double
mlngCounter = mlngCounter + 1
(Central section of code not shown)
Me.txtResult.Value = dblSumOfNumbers
CleanUpAndExit:
Exit Sub
tip
Always use the labels
ErrorHandler: and
CleanUpAndExit: in every
function and sub routine.
There’s no reason to give a
custom name to every label
even though you’ll see later
that wizard-generated code
does this.
Using the same error handler
labels keeps your code
consistent and improves
productivity as you can cut and
paste error handling code from
one sub to another.
Session5e
note
There’s nothing more
unprofessional (from a client’s
perspective) than an
application that frequently
crashes.
One of our most important
quality standards (stated in
Appendix A – The Rules) states
that:
“Error Handling must be
implemented in every sub and
function without exception".
Programmers often argue that
some code is so simple that it
can never fail so does not need
error handling. While this may
be true in some cases there’s
nothing wrong with a catch-all
approach. If absolutely every
sub has error handling code
you cannot possibly confront
your user with a confidence-
sapping runtime error.
When you take this approach it
is comforting to find that those
bullet-proof subs that couldn’t
possible fail often do, but when
they do the error is always
elegantly handled.