Breakpoints are simply places in your code that pause execution of code. For example, to check the value of a variable curTotalCost midway through the following procedure, you'd need to use the Debug.Print statement (as in the following code) or set a breakpoint.

Sub HowMuchCanWeSpend()

Dim curTotalPrice As Currency

Dim curUnitPrice As Currency

Dim intNumSocks As Integer

Dim i As Integer

curUnitPrice = 3.5

intNumSocks = InputBox( _

"Please enter the number of pairs of socks youwant."

"Pairs of Socks")

For i=1 To intNumSocks

curTotalPrice = curTotalPrice + curUnitPrice


Debug.Print curTotalPrice

End Sub

This code prints in the Immediate window the amount you'll spend for the total sock purchase. That's great, but what if you want to see how your total expense is adding up as you go? You can certainly add a Debug.Print statement within the For...Next loop, but you can also set a breakpoint anywhere in the procedure. Once the breakpoint is reached, you can use the Immediate window to check the value of your variables. You can set a breakpoint on any line of code except for Dim statements and comments.

The simplest way to set a breakpoint is to click in the left margin of the Code window. A brick-colored dot appears in the margin and the corresponding line of code is highlighted. To clear a breakpoint, click the left margin again in the same spot. You can also set and clear breakpoints by placing your cursor in the desired line of code and selecting Debug O Toggle Breakpoint or pressing F9. When you run the code, every time the breakpoint is reached, code execution stops and VBA waits for you to decide what to do next. You can choose from the following options:

□ Check the value of variables in the Immediate window. When your code reaches a breakpoint, the value of all variables is retained. You can check the value of any variable by using the Debug.Print statement or the ? character within the Immediate window.

□ Use your mouse to hover over any variable in the current procedure. The value of the variable is displayed close to the mouse cursor.

□ Press F5 or select Run O Continue to continue code execution. Execution proceeds until the next breakpoint or the end of the procedure.

When VBA encounters a breakpoint, it pauses execution immediately before the line of code is executed. The line of code that contains the breakpoint is not executed unless or until you choose to step through the code using the F8 key.

Was this article helpful?

0 0

Post a comment