Monday, 1 March 2010

Debug.Print Demystified

You can insert Debug.Print statements anywhere in your VBA code. These will appear in the Immediate Window in the VBE (just strike Cntrl-G to display the results of these statements). From Excel 2000, you can also do Debug.Asset (condition) which will break the code if the assertion is violated.

Debugging unfamiliar VBA can be made easier by the use of Debug.Print.

For example, macros may hang and go into infinite loops. This can be due to lack of "Option Explicit". For example, suppose you loop through the numbers I from 1 to 30. You call a function that also uses the loop counter I, which causes I to get stuck at 15 in your main loop - infinite loop! Debug.Print can help you find these problems in loop counters quite easily.

Cntrl-G is your friend!

If you want to take VBA debugging to the next level, you can also use conditional compilation using the #const directive, together with #if and #end if macros. for example:
#CONST DEBUG_ = True
#If DEBUG_ Then
Debug.Assert (X<109)
#End If

No comments: