Like any other VB method, you must use the dot operator syntax to call the
method from its object. Because you don’t need to declare an object variable
to use the Debug object, you just invoke the method from the object itself, like
this:
Debug.Print "Eat at Joe’s."
If this statement were in your code, the message "Eat at Joe’s."
would appear in the Immediate window when this line executed in your code. More
useful messages might tell you that a particular function has been entered, or
into which branch of a conditional test your code has entered. For instance:
LISTING 18.2
MORE USEFUL MESSAGES
Select Case iConditionTest
Case 1
Debug.Print "Branched into Case 1"
‘ real case 1 code follows
Case 2
Debug.Print "Branched into Case 2"
‘ real case 2 code follows
‘ Case etc.
End Select
Although you could also find out this kind of information by singlestepping
through your code in Break mode and observing the path of execution, using the
Immediate window to display signpost messages saves you the bother of manually
stepping through the code. It is especially handy when all you wanted to know
was the information displayed in the signpost itself. If you just want to know
whether your code branches into condition A rather than condition B, and the details
of execution are otherwise unimportant, a message in the Immediate window is much
more convenient than single-stepping.
Because this is a debugging technique, you may recall a lesson from the chapter
on conditional compilation that explains how to keep your debug code from inadvertently
making its way into a product release. One way to prevent your Debug.Print statements
from appearing in the release version of your programs might be to wrap in a conditional
compiler block like this:
#CONST DebugConstant = 1
#If DebugConstant Then
Debug.Print "This message only appears when
DebugConstant is True"
#End If
Fortunately, Microsoft did everyone a favor that saves the bother of writing
a conditional compiler block every time you want to use Debug.Print. Statements
involving the Debug object are effectively stripped out of your program when it
is compiled.
NOTE - When Debug Messages Appear: The Debug.Print
message appears only when testing an application in the debugging environment.
When a user runs an application, it is not running in the debugging environment,
so there is no Immediate window to display the message.
-
Formatting Debug.Print Messages
-
Displaying Data Values