Chapter 10.
Debugging and Error
Handling
BMGT 302
Business Application Programming
Scott Hudson
Debugging
Bugs
Errors in your program
Debugging
The process of locating and correcting the errors in the program
3 types of errors
Syntax errors
Runtime errors
Logical errors
Scott Hudson BMGT302
Syntax errors
occur when you spell something wrong, omit
a keyword, or commit various other
grammatical errors.
Visual Basic Editor (VBE) typically detects
them immediately, colors the offending line
red, and displays a warning in a message box
If variable1 > variable2
End If
! Compile Error
Expected Then
Scott Hudson BMGT302
Runtime errors
occur when there is some- thing wrong with your code, but
the error is not discovered until you run your program
Divided by zero
Array index out of range
Memory overflow
Scott Hudson BMGT302
What if user enters 20?
Scott Hudson BMGT302
Correcting your code
Scott Hudson BMGT302
Run time errors
May be caused by unexpected user
inputs
Open BankAccount.xlms
Type 0 and interest rate, and run
findYears
Scott Hudson BMGT302
Logical errors
You run the program, it produces
some results, but the results can be
totally wrong
No warning signs
you often dont even know that you
made an error
Scott Hudson BMGT302
Scott Hudson BMGT302
VBE debugging tools
Scott Hudson BMGT302
10
Breakpoints
You can set and clear breakpoints in your code
A breakpoint is a line of code that the program will pause
when it is reached
This allows you to examine variables and see if they are what you
expect
You can set a breakpoint by:
Place cursor on the line you want, click hand symbol
Place cursor on the line you want, click toggle breakpoint in
Debug toolbar
Place cursor in the gray margin to the left of the line you want and
click
Reset by toggling again
Breakpoint set
Scott Hudson BMGT302
11
Breakpoints
With a breakpoint, your code will run until the
execution reaches that statement then it halts.
Program enters break mode
At this point, you can:
Examine the value of variables
mouse over/hover over a variable that appears in
the code. The value of the variable appears in a popup
Request the value of any variable via the immediate
window (example: ? cellCount)
Step through the code one line at a time to see what
is happening
Scott Hudson BMGT302
12
Breakpoint Example (Count High Sales.xlsm)
Breakpoint set,
yellow means
code has stopped
here
Variables queried In Immed. window
Scott Hudson BMGT302
13
Breakpoint Mouse-over
You can move your mouse over a
variable while in break mode and
VBE will display its value
Scott Hudson BMGT302
14
Watch Mode
Another valuable technique is to enable Watch
Mode
Watch Mode allows you to set conditions for
when either a break should take place or
when something should be displayed
Classic example: you have a big loop (like
1000) and something wrong seems to
happen around 900.
Without a Watch Mode, you would have to
manually go through 900 iterations
(stopping at a break point each time) before
you got to where you wanted
Scott Hudson BMGT302
15
Watch Mode
Turn on Watch Window
Watch
Window
appears
Scott Hudson BMGT302
16
Add Watch
Turn on the Add Watch dialog box from the
Debug choice on the main toolbar
Scott Hudson BMGT302
17
Add Watch
1. Put in a condition
2. Select where
3. Select action
Scott Hudson BMGT302
18
Step Into, Step Over, Step Out
One powerful debugging technique uses
breakpoints in conjunction with the step
buttons
Step Into, Step Over, Step Out
Scott Hudson BMGT302
19
Step Into
The most used button is Step Into
When a Sub stops at a breakpoint, it can
be extremely useful to then step
through the remaining code, one
statement at a time
Step Into does this
Each click on the Step Into button executes
only the next statement
You can watch what happens as a result of
that statement execution in the immediate
and watch windows or by using a mouse
over
Scott Hudson BMGT302
20
Step Over
When executing in Step Into mode,
you may encounter a call to another
Subroutine
It is likely you will not want to execute
this subroutine one line at a time as that
is time consuming
A click on the Step Over button will have
VBA execute that subroutine at full
speed, stopping again when the code
returns
Scott Hudson BMGT302
21
Step Out
Similarly, at some point you may
want to go back to full speed mode
One click on Step Out and the rest of
the Sub is executed at full speed
Often used in loops with a breakpoint
Stop at breakpoint
Step Into several statements to see
what is happening
Step Out to execute at full speed until
the breakpoint
is hit
again
Scott Hudson
BMGT302
22
Exercise
Exercise: debug the average example. Open
Debug Average.xlsm
Scott Hudson BMGT302
23
Debugger Tools
The Debug Tools are extremely powerful and
will save you large amounts of time and
frustration
They are not hard to learn/use
Take the time to work with them and learn
how to use them IT WILL PAY OFF!
Note: the VBA debug tools are extremely
similar in function to such tools in other
languages.
Learn one, learn them all.
Scott Hudson BMGT302
24
Errors
The reason programming is so difficult and
why much commercial software has
bugs is that it is impossible to predict
exactly how all people will use the
application.
People will make mistakes when they use an
application
People will follow a path that the programmer
did not predict (and plan for)
Designers/programmers cannot predict every
possible input
Scott Hudson BMGT302
25
Errors
However there are things a sensible
designer can do to:
Prevent certain inappropriate actions from the user
Detect inappropriate actions and at least keep the
application from crashing
The first item above is usually performed by
doing input validation checking
The second is accomplished by trapping an
error when it occurs and seeing if recovery is
possible
Scott Hudson BMGT302
26
Need for input validation
People are . People. They make many mistakes.
Good designers protect themselves (the
application) by checking/validating user input
Invalid dates (13/35/2011)
End date before start date
entering decimals when the program expects integers,
alphas instead of numbers, etc.
Scott Hudson BMGT302
27
Validating User Input
Typically, user input is checked/validated
when the user clicks on a button to submit
input (OK, Submit, Enter, whatever)
To validate, you would put some input check
code within the button_click event code
Scott Hudson BMGT302
28
Validate Code
Private Sub CommandButton1_Click()
Dim ctl As Control Control would be TextBox, Button etc..
Dim begDate As Date, endDate As Date
'test to see if a date has been entered in the date fields
For Each ctl In Me.Controls
Look at all Contols
If TypeName(ctl) = "TextBox" Then
If Control is a form
If ctl.Value = "" Or Not IsDate(ctl) Then
MsgBox "Enter a valid date.", vbInformation, _ "Invalid
Entry"
ctl.SetFocus
Exit Sub Exit CommandButton1_Click() Subroutine
End If
End If
Next ctl
'a data has been entered, check to see if it's within right
begDate = Me.TextBox1.Value begDate and endDate are
Data Type as Date
endDate = Me.TextBox2.Value
Scott Hudson BMGT302
29
Validate Code cont
Scott Hudson BMGT302
30
Note:
The code on the previous page displays several new concepts:
1.
2.
3.
4.
5.
6.
A ctl (control) object
This relates to all the controls on a form
Me reference
Points to current part of the application. In this example, the
form
If TypeName(ctl) = TextBox
Allows you to determine what kind of control you are looking at
ctl.value =
Many controls have input. This allows you to check if anything
has been typed in or it is blank ()
Not IsDate(ctl)
After checking if something is not blank, this code checks if the
input is a date type
ctl.SetFocus
This method sets the cursor on the selected control
Scott Hudson BMGT302
31
On Error Statement
VBA provides the On Error statement
This is used to trap an error that causes
VBA to stop your code. Examples:
Deleting something that doesnt exist
Looking for a file that doesnt exist
Data type mismatch
Protected cell violation
With this you can:
Either ignore the error and continue
Jump to an error handling routine that you write
Scott Hudson BMGT302
32
On Error Statement
On Error Resume Next
On Error GoTo <lable>
On Error GoTo 0
Scott Hudson BMGT302
33
Ignoring an Error
This statement, once executed
anywhere in your code, will put your
program in ignore error mode
On Error Resume Next
Basically, if a statement is executed
that causes an error that would
normally force VBA to stop, that
statement is ignored and execution
continues to the next statement
Scott Hudson BMGT302
34
Ignoring an Error
Example:
On Error Resume Next
Application.DisplayAlerts = False
Worksheets(Results).Delete
If worksheet Results does not exist, no
error is given and the code continues
This must be used carefully.
If a divide by zero happens, you should not ignore
this as you will be making incorrect calculations
from now on.
Scott Hudson BMGT302
35
Error Number
When an error takes place, you can receive and
check the error number to determine the type of
failure.
Error number is non-zero in event of an error
You can check this with an IF test
Err.Number is Built-In
If Err.Number <> 0 Then
do something about the error (msg?)
Example: delete a worksheet that doesnt exist = error 9
divided by zero = error 11
Scott Hudson BMGT302
36
Scott Hudson BMGT302
37
On Error GoTo <lable>
VBA allows you to define a code label
Code labels act like a bookmark and can be
any name or number you want, followed by a
colon :
A GoTo statement jumps to that label
Similar to a Call Subroutine EXCEPT the routine does
NOT return to the statement after the call
After the On Error GoTo <label> statement
is excecuted, it is always on. Execution
jumps to the specified error routine if ANY
error takes place.
Turn off with On Error GoTo 0
Scott Hudson BMGT302
38
Example: On Error GoTo
Note: the Exit Sub is critical -otherwise, the error routine
will be executed at the end
of the subroutine even when
there is no error
Scott Hudson BMGT302
39
Example: On Error GoTo
Used
alone,Resumecauses
execution to resume at
the line of code that
caused the error.
In this case you must
ensure that your error
handling block fixed the
problem that caused the
initial error.
Scott Hudson BMGT302
40
On Error GoTo 0
default mode in VBA
when a run time error occurs VBA should display
its standard run time error message box
no enabled error handler
Scott Hudson BMGT302
41