Using the Debug Object

The Debug object contains two methods that we can use to debug our code: Print and Assert. The Print method directs output to the Immediate window, and the Assert method lets us set a condition that puts our code in break mode if the condition fails.


Whereas the MsgBoxfunction interrupts the execution of our code, the Debug.Print method allows the code to run through to finish, sending its output to the Immediate window. This is especially useful when debugging code in a loop.

1. As a very simple example, enter the code from Listing 7-3 on Standard Module1 in the DebugExample01.xlsm project.

Listing 7-3. Simple Routine Using Debug.Print to Send Output to the Immediate Window

Sub DebugLoop() Dim i As Integer

Debug.Print "Debug loop: " & i Next i End Sub

2. Run the code in the Immediate window, as shown in Figure 7-11, by typing the following command and pressing Enter:


Debug loop: 1

Debug loop: 2

Debug loop: 3

Debug loop: 4

Debug loop: 5

Debug loop: 6

Debug loop: 7

Debug loop: 3

Debug loop: 9

Debug loop: 10

Debug loop: 11

Debug loop: 12

Debug loop: 13

Debug loop: 14

Debug loop: 15


Figure 7-11. Debugging a loop

Imagine checking the value of the variable i with a message box. No fun there, and that's a small loop! Let's modify the BirthYear function to use Debug.Print instead of MsgBox so our code can run without interruption and still show us the variable values as the code runs.

1. On Standard Module1, replace each instance of MsgBoxwith Debug.Print.The code should look like Listing 7-4.

Listing 7-4. BirthYear Function Using the Debug.Print Method

Function BirthYear(Age As Integer, HadBDay As Boolean) Dim iReturn As Integer Dim iCurrYear As Integer iCurrYear = Year(Date) iReturn = iCurrYear - Age

Debug.Print "Current Year: " & CStr(iCurrYear) Debug.Print "Birth Year before If: " & CStr(iReturn) If Not HadBDay Then iReturn = iReturn - 1 End If

Debug.Print "Birth Year after If: " & CStr(iReturn)

BirthYear = iReturn End Function

2. In the Immediate window, run BirthYear, passing in False to the HadBday argument, by typing the following:

?birthyear(30, False)

3. Press Enter to run the code. The output to the Immediate window is shown in Figure 7-12.

?birthyear(30, False}

Current Year: 2007 Birth Year before If: 1377 Birth Year after If: 1976 1376

jlu -ir

Figure 7-12. Output of BirthYear function sent to Immediate window

We see the three messages we were looking for, plus the bottom line shows us the return of the function. Here we see that our code did fall into the If...End If statement where it subtracted one from the result because the birthday did not yet occur this year.

0 0


  • mariam
    How to enter a for loop in vba immediate window?
    8 years ago

Post a comment