Breakpoints are simply places in your code that pause execution of code. For example, if you want to check the value of a variable curTotalCost midway through the following procedure, you'd need to use the Debug.Print statement 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 you want.", "Pairs of Socks") For i = 1 To intNumSocks curTotalPrice = curTotalPrice + curUnitPrice


Debug.Print curTotalPrice End Sub

The preceding 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 will appear in the margin and the corresponding line of code is also 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 select Toggle Breakpoint from the Debug menu 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 Continue from the Run menu to continue code execution. Execution proceeds until the end of the procedure or until the next breakpoint is reached.

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

Was this article helpful?

0 0

Post a comment