5. Change the second = to a minus sign (-) so that the code reads as follows:
iReturn = iCurrYear - Age
6. In the Immediate window, run the code again (clicking OK on each message box,
which should now hold the correct value for iReturn). The result should look like
Figure 7-10.
Figure 7-10. The correct value is returned.
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.
CHAPTER 7 n DEBUGGING AND ERROR HANDLING 257
Debug.Print
Whereas the MsgBox function 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
For i = 1 To 15
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:
debugloop
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.
Pages:
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247