Microsoft Office Tutorials and References
In Depth Information
Dealing with Logical Errors
Imagine writing a procedure that’s supposed to make some changes in all
the records in a table with the help of a loop embedded in your code. When
you run the procedure, though, the expected result doesn’t happen. You can
put a Debug.Print statement inside the loop to display the current value of
some counting variable within the loop, as in this example:
Function Whatever ()
For intCounter = LBound(myArray) To UBound(myArray)
‘Show value of intCounter with each pass through loop
Debug.Print “intCounter = “ & intCounter
[maybe more code]
If you run the procedure with the Immediate window open, the Immediate
window displays something like this:
intCounter = 0
intCounter = 1
intCounter = 2
If some problem exists with the loop’s conditional expression (the logic that
makes the loop repeat x times), you may just see something like the following:
intCounter = 0
The preceding output tells you that the loop repeats only once, with a value
of 0. You need to go back into the code, figure out why the loop isn’t
repeating as many times as you expect, fix that problem, and then try again.
After you solve the problem, remove the Debug.Print statements from
the code, because they serve no purpose after the debugging phase is done.
Optionally, you can comment out the Debug.Print statement by adding an
apostrophe to the beginning of its line, thereby making it appear to VBA to
be a comment. After you comment out a statement, it’s no longer executed
in the code. To reactivate the Debug.Print statement in the future,
uncomment it by removing the leading apostrophe.
Another way to check for logical errors in code is to slow things way down
to see exactly what’s happening, step by step, while the procedure runs.
To do this, you set a breakpoint at the line of code, right where you want to
start slowing things down.