12.15 Debugging: F8, Breakpoints, Immediate and Locals Windows
Raja's report marks two deliveries late, but he can see only one took more than fifteen minutes. His macro runs without an error, so he pauses it before the comparison and reads the exact values. Then he uses the same approach to find why a plan reserves an extra row after every city group.
Begin with one prediction a running program can disprove
Three inputs are enough to show a boundary error
Imagine a fictional delivery team reviewing practice rows similar to a Blinkit dispatch. The names and actions are made up. One row took exactly fifteen minutes, another took eighteen and a third took seven. The stated Late definition is more than fifteen. That means only eighteen qualifies. If the workbook says two, trace how the procedure reached its decision instead of immediately changing search ranges or clearing old output.
- Break mode: Execution is paused at a point where VBA can show the next statement and current values. The highlighted next instruction has not yet run on that pause. Check the highlighted line before inferring which variables have been assigned.
- Breakpoint: A deliberate pause requested on an executable statement. You can set it in the code window margin or toggle it through the Debug menu. When the running procedure reaches that line, inspect the current state before executing it.
- Step Into: Execute the next statement with detailed stepping. If that statement calls a function, the debugger can enter the function and stop at its next instruction. This is useful when the wrong value could come from the helper's internal comparison.
- Step Over: Execute a called procedure as a unit and return to the next instruction in the caller, subject to other pauses and errors. It is useful if you already trust a helper and want to check whether the caller supplied the right values.
- Step Out: Finish the current procedure and pause back in its caller when the debugger can. The remaining instructions are still executed. Check them if they can write a result or change a setting before using the command.
Use the Debug menu when keys depend on the device
In the Windows examples F8 is Step Into, F9 toggles a breakpoint, Shift plus F8 steps over, and Ctrl plus Shift plus F8 steps out. Run to Cursor is often Ctrl plus F8 and runs until the chosen line can be reached. A long conditional branch can mean a selected line is not part of the current execution. Use the actual menu labels in your editor if function keys are mapped differently, particularly on Mac. Use an approved desktop client. The tests below target your own disposable workbook.
Compile checks source code structure and declared names, but it cannot tell whether fifteen is supposed to be included. Read the worksheet rule and the intentionally incorrect condition. The runtime debugger can display values along the path. A successful compile plus a correct test is stronger than a successful compile by itself.
Remember: Record the expected answer and the first point where execution differs. The first cause often occurs earlier than the visible wrong total.
Distinguish the current view from the current execution
Choose a window for what you need to read
| Window | Useful for | Limit |
|---|---|---|
| Locals | Variables in the active procedure while paused | Scope changes when you enter a helper |
| Immediate | Read-only expressions and Debug.Print lines | Old messages may remain |
| Watch | One selected expression, perhaps with a conditional pause | Context and side effects matter |
| Code | The exact next statement and source location | Appearance alone cannot prove a cell was written |
The Locals window refreshes the values for the current context. When you step into a function you can see its parameters, which may have names different from the variables in its caller. When a procedure has finished, its ordinary local variables are no longer available from outside its call. Use the latest diagnostic output or the worksheet to confirm the final result.
The Immediate window can execute statements as well as evaluate expressions. Use simple read-only expressions beginning with a question mark in this lab. You can see traces from previous runs below or above the current output. Identify the exact invocation and the values from its current pause. Watch expressions can be useful when reviewing a simple numeric variable or Boolean expression, but avoid watching a procedure call that could do work or change state.
Lab one. Find the first incorrect condition
Make the expected result visible beside the macro's answer
Create DebugPractice.xlsm yourself in approved desktop Excel and add a worksheet called Timing. Use rows two through four for three completed delivery examples. Enter the identifiers in A2:A4 and their numeric durations in B2:B4. Put a label such as Late count in D2 and reserve E2 for the macro output. Put a separate worksheet formula in G2 to check the documented rule. Give the practice worksheet a short marker in G4 that should remain untouched.
| Order ID | B minutes | Expected late? |
|---|---|---|
| QC-15 | 15 | No |
| QC-18 | 18 | Yes |
| QC-07 | 7 | No |
G2: =COUNTIF(B2:B4,">15")
In the practice workbook's standard module enter the exercise code. It has an intentional defect in its private comparison function. Keep the incorrect version only for this exercise until you have found why it fails. The rest of the procedure reads the three numeric inputs and stores one count. Do not replace an existing macro on a report workbook while learning to pause and step.
Option Explicit
Public Sub TraceLateCount()
Dim ws As Worksheet
Dim rowNo As Long, lateCount As Long
Dim raw As Variant, limit As Double
Set ws = ThisWorkbook.Worksheets("Timing")
limit = 15
For rowNo = 2 To 4
raw = ws.Cells(rowNo, 2).Value2
If VarType(raw) <> vbDouble Then
MsgBox "Enter numeric minutes in Timing row " & rowNo
Exit Sub
End If
If IsPastCutoff(CDbl(raw), limit) Then
lateCount = lateCount + 1
End If
Debug.Print rowNo, raw, lateCount
Next rowNo
ws.Range("E2").Value2 = lateCount
End Sub
Private Function IsPastCutoff(ByVal elapsed As Double, _
ByVal limit As Double) As Boolean
' Intentionally incorrect until the lab's correction.
IsPastCutoff = (elapsed >= limit)
End Function
Pause before the helper and inspect the first row
- Verify G2 displays 1 from the worksheet formula. In the editor place a breakpoint on the If line that calls IsPastCutoff. Run TraceLateCount from the exercise project. It should pause just before the first use of the comparison. The result E2 should still be empty or show a prior run's count. The final assignment has not been reached.
- Open Locals. At this first pause rowNo is 2, raw is 15, limit is 15, and lateCount is 0. Read the currently highlighted line to see why. The current row's input has already been read, but the evaluation has not added to the count yet.
- Use Step Into at the helper call. In the private function observe its current parameters elapsed and limit. Both are fifteen. While paused in the helper, enter the two read-only expressions below separately in Immediate. Expect True for the first and False for the second. The statement in the original helper uses the first comparison, although the documented rule calls for the second.
- Use Step Out if you want to finish the helper, then inspect the next instruction and the caller's count. The helper's result can be True before the caller adds one. Step through the counting statement and confirm it goes from zero to one even though this exercise row is exactly at the cutoff. That is the first divergence from the expected result.
- Continue the practice run if you want to see its full incorrect result. Under the intentionally defective code, the row counts are one, two and two. E2 becomes 2 and the separate worksheet check stays 1. If you keep the breakpoint, VBA pauses at each row. Use the debugger menu to toggle it once the relevant state is understood.
? elapsed >= limit
? elapsed > limit
Apply one repair and retest the same fixture
Finish or reset the disposable routine before editing. Replace the incorrect line with the strict comparison below. Compile the project if the menu permits it. This change does not move the outcome to a different worksheet. It only makes the comparison match the agreed rule. Reset the previous E2 result manually to make the new write visible, and rerun using the same first record and the documented fixed limit.
IsPastCutoff = (elapsed > limit)
At the first row the function now supplies False, so the count stays zero. The second row with eighteen increases it to one. The third row with seven leaves it at one. E2 should now match G2 and the marker in G4 should still be present. Try changing the first duration to 15.01 and verify that the result becomes two after the macro reruns. Restore the first value to fifteen before recording your final evidence.
See which statement first diverges from the rule
Start with a known result
The sample durations are 15, 18 and 7. Only 18 is above 15, so the independent worksheet answer is one.
Enter the called comparison
Step Into lets you read elapsed and limit. Both are 15 in the first iteration.
Observe the two conditions
Greater than or equal is true. Strict greater is false. The current code uses the first, while the stated rule uses the second.
Repeat the known test
Change only the condition and restart the routine. The repaired result is 1 and the separate check still reports 1.
Lab two. Catch a header in an append-position calculation
Trace a plan without copying or deleting records
After grouping rows from the practical macro example, the analyst needs to know the first unused destination row for each batch. The destination already has a table header on row one. Pune contributes four actual records and Nashik contributes two. A third scratch group has no records. Each input count below includes its own header. The plan must consume rows only for data. This lab prints the expected positions and changes no worksheet values.
| Group | Rows including header | Actual records |
|---|---|---|
| Pune | 5 | 4 |
| Nashik | 3 | 2 |
| Empty group | 1 | 0 |
Make a worksheet called Groups in DebugPractice and put the values above in columns A and B. Column C can contain notes or the independent record counts. Do not reuse the actual city output sheets for the debugging test. Here is the controlled faulty version. It intentionally advances by the header-inclusive count, so the printout describes the bug without creating extra rows in any report.
Public Sub TraceAppendPlan()
Dim ws As Worksheet
Dim groupRow As Long, destinationRow As Long
Dim rowsWithHeader As Long, dataRows As Long
Dim raw As Variant
Set ws = ThisWorkbook.Worksheets("Groups")
destinationRow = 2
For groupRow = 2 To 4
raw = ws.Cells(groupRow, 2).Value2
If VarType(raw) <> vbDouble Then Exit Sub
If raw < 1 Or raw > 11 Or raw <> Fix(raw) Then Exit Sub
rowsWithHeader = CLng(raw)
dataRows = rowsWithHeader - 1
Debug.Print ws.Cells(groupRow, 1).Value2, "Before", destinationRow, dataRows
' Intentional defect: the source header is counted again.
destinationRow = destinationRow + rowsWithHeader
Debug.Print "After", destinationRow
Next groupRow
End Sub
Choose the line where the calculation crosses the boundary
- Set a breakpoint on the statement that adds rowsWithHeader to destinationRow. Launch TraceAppendPlan in the correct workbook. At the first pause use Locals to read groupRow 2, rowsWithHeader 5, dataRows 4 and destinationRow 2. Confirm the caller already subtracted one to find four records but never used that value in the increment.
- Predict the correct position before you step. Four records starting at row two would occupy rows two, three, four and five. Row six is next. Step over the faulty assignment in the paused run. It instead makes destinationRow seven, leaving one unused position after the group's data. The highlighted next Debug.Print line has not yet executed.
- Continue through the remaining two groups or use Run to Cursor on the next executable line you want to inspect. After the second group the wrong position is ten. The header-only group advances the wrong plan once more to eleven, even though it contributes no data.
- Finish or reset the disposable procedure and replace the one faulty increment with the line below. Run it again. The new after values are six, eight and eight. Compare them with the original printout and explain why the final group cannot advance the position. Keep the G4 marker from the other sheet unchanged.
- Practice a Watch for the local variable destinationRow in this procedure if your editor offers it. Set the context to TraceAppendPlan so another procedure's local variable cannot be confused with it. A simple Watch expression can show the current value at each pause. Remove the Watch or temporary breakpoints when you are done so the next test can start cleanly.
destinationRow = destinationRow + dataRows
Translate the counter into a result another reader can check
If the first destination data row is two and a group has four records, the last row it would fill is five. The next unused row is six. After two more records the last occupied position becomes seven and the candidate unused position becomes eight. In this lesson we only model the plan. A full combine still has to verify real records, keys and output ownership before writing anything. The rehearsal shows the arithmetic without risking an output dataset.
If another analyst says row eight contains six total data rows, check their wording. There are six planned records across rows two through seven. Row eight describes the first available position after them. One final count can be derived from either the known data row counts or the candidate bound minus the start. With eight minus two, the result is six. Showing both perspectives can help identify an extra record, gap or duplicated header.
Read the paused state without disturbing it
Use the smallest observation that tells you enough
- Variable hover: If the editor displays a value when you point at a variable, use it as a quick look at the active scope. Some builds or settings may differ. The Locals or Immediate pane gives a deliberate check. Do not assume a same-named variable in another routine is the one you just inspected.
- Code highlight: A marker for the next statement precedes its effect. A red breakpoint marker indicates where you requested the pause. The chosen editor colors may differ, so read the current location and the actual statement. After stepping, compare the next line and value again.
- Read-only Immediate query: A question-mark expression can print the current value of a local variable in a relevant context. A statement that sets a cell or changes a variable can alter the experiment. Keep the inquiry to tracing the existing state so a later rerun means the same thing.
- Watch expression: Read a simple expression like destinationRow or a comparison without side effects. Some watch settings can break when a value changes or an expression becomes true. Check that the expression belongs to the correct procedure and clear temporary watches when finished.
- Reset: Reset ends the current execution. It does not undo workbook writes or guarantee that normal cleanup code ran. In the first exercise the easiest safe test ends before the one result write, or uses a clean copy to verify exactly what did happen.
Before continuing: Name the next statement and say whether it changes a number in memory, writes a diagnostic or edits the worksheet. Keep that distinction as you move among debugger windows.
Design a reproducible debugging plan
Show the expected trace, then observe it
The two labs share the same method. Use exact inputs and predict the pieces before you launch the code. Choose a point where a particular decision can differ, such as the call with elapsed equal to fifteen or the calculation adding group rows. Observe the value before the statement. Execute only that statement or the called helper. Read the new value and compare it with the predicted after state. This separates a wrong input from the statement that uses it.
- Capture the input: Record the workbook name, worksheet, record ID and cell representation. The data displayed as 15 may have an underlying 15.01 if the cell is formatted without decimals. Read actual numeric input using the source check before deciding which operation failed.
- Write expected before and after values: Start with row two and lateCount zero. At exactly fifteen the strict comparison should leave the count zero. In the group example the count inclusive of the header equals five and the current next destination row equals two. The correct after value is six.
- Choose the relevant step method: If the helper itself might be wrong, step into it. If you already checked it and want to see the result in the caller, step over it. If the routine contains effects outside your intended proof, start with a copy or a read-only test before asking the debugger to finish the action.
- Fix one cause at a time: Change the actual bad comparison or row increment. Reset to the same fixture and rerun before trying other changes. Verify the independent outputs. Using a new dataset and a new condition together would make it harder to know which edit fixed or introduced the result.
Plan a narrow failure variant with unchanged output
In the Timing fixture, change B3 to text in the practice copy while keeping B2 numeric. The control code's guard returns after reporting the bad input row. Since the write to E2 is after the iteration, any existing E2 stays unchanged. The Immediate window might still include an earlier trace from row two. A developer needs to read the current failure and its location rather than treating a later-looking count in the worksheet as a fresh result. Restore eighteen as an actual numeric value and test the successful output again.
In the Groups fixture, change the last count from one to zero. The code requires at least the source header's one row for this teaching shape. It exits before the third group's calculation. The editor can keep the first two trace pairs. Write down which groups were processed and which was rejected. A different report format that stores data-only counts could accept zero, but it needs a different contract and would not subtract the header here. If another person adapts the code without changing the rule, a fresh test should expose it.
Use expected totals and control cells as separate evidence
After repairing the first routine, the final count at E2 and the independent worksheet G2 both equal one. That verifies the stated threshold against these three known values. The unchanged marker shows a different fact about the effect on workbook areas. The debugger trace shows where the corrected result changed. Capture all three observations so the learner can reproduce the exact test. A passing count alone cannot prove every row was visited if the omitted row happened not to qualify.
To catch a skipped record, make one more check with distinct durations. Suppose you change the last record, QC-07, to 16. The source check now expects two late records. Rerun the corrected procedure and verify two. If it still gives one while the first two row computations look right, examine the ending index and the latest printed row. This tests the loop's inclusion of the last record rather than the earlier corrected comparison. Restore seven after the test. Record which input changed and what the result should do.
Read diagnostic evidence without creating another failure
Compare a paused run with completed and repeated runs
A breakpoint before the final E2 assignment is useful for confirming that all calculations have finished, but the worksheet still displays an earlier value at that point. You can look at lateCount and the old result separately. To observe the new write, advance one more statement in the approved practice file. Record whether the procedure then completed. If you stop before the line, any visible number in E2 comes from another action or an earlier run. Keep this distinction when sharing an editor screenshot or a note.
The Step Out command finishes the current procedure. If you run it while inside a helper that writes data, those remaining writes may happen. This lesson's comparison helper returns one Boolean value and does not change a workbook cell. The group rehearsal does not write at all. Use small, known scopes while learning the debugger, and consider reading the remaining statements before choosing a command that completes them. A pause is an observation point, not a safety rule against changes.
Use a Watch only when it matches a clear question
A simple Watch shows a selected variable or expression at each break. If you configure it to pause when a Boolean expression becomes true, the editor may stop somewhere you did not place an explicit breakpoint. Choose a variable meaningful to the current procedure, such as destinationRow. For the unexpected third group, watching an expression such as “dataRows is zero” can help you locate its before-state, when your particular editor and watch scope support that option. A breakpoint at the increment still gives the clearest statement-level test.
After learning the first fixture, remove just your temporary breakpoint or choose a clear-all action only in the isolated project when appropriate. Release any Watch you added, then repeat the approved procedure once to confirm it can complete without pausing. A support note saying “the macro stops unexpectedly” may describe a remaining debugger condition instead of a source failure. Read the displayed location and check what requested the pause before correcting code.
Compare first, middle and last outputs
In a full combine routine, a report can end with a missing row because the input extent was wrong or because an append position skipped a slot. Examine the actual input body counts independently. Then use the known group sequence and inspect the position before and after each transfer. The debugging exercise proves the arithmetic in a small plan. A complete write test still needs the correct source records and approved destination. Applying the one-line repair to a different report without reading it can create a new error.
This is especially important for an empty group. A real data collection can have zero valid rows, one header row or a worksheet with a reserved template area beyond its records. Its UsedRange height is not always the number of rows that should be copied. This lesson uses prepared group sizes as inputs. For the real version choose and validate the row-count rule before reading the append position. Verify that a header-only group adds zero. Then choose one group with a gap or malformed record and specify how it is handled.
Make the result reproducible: Write the workbook name, test input, exact next statement at the pause, source of the independent expected result, and a note about which effects occurred. A short trace is more useful than a screenshot with no entries identified.
Verify the repaired behavior with one extra independent record
Test whether the term that changed was the intended one
For the timing example, add another practice test without changing the range boundaries. Temporarily replace the first duration fifteen with 14.99 and run the repaired function through the macro. You still expect one qualifying row. Now use 15.01 with the same position. The expected count becomes two. Read the exact numeric contents and confirm both results against the independent worksheet formula. A change exactly at the known boundary and one just beyond it show that the comparison had the intended strictness. The first and last source rows have enough variety to reveal accidental reuse of one row's value.
Suppose both comparisons in the Immediate window appear to be True even for a record whose display is fifteen. Check the actual local value and formula bar. A value such as 15.01 can look like fifteen under a no-decimal cell format. You cannot conclude that a comparison is wrong until you know the operands. Verify that you entered the query in the relevant procedure while paused. Then compare the correct row ID and amount convention. Preserve the original small fixture so you can distinguish a formatting surprise from a logic defect.
Verify an empty group in the middle rather than only at the end
For TraceAppendPlan, try a separate known fixture with input heights five, one and three. Those mean four, zero and two data rows. Begin the destination at row two and predict six, six and eight. A correct plan leaves the same position available after the second group, then uses it for the third. The bug using source heights would give seven, eight and eleven. Notice the buggy after position increases even for the empty group in the middle. This preserves a useful third clue if someone later hides the append plan's final value.
The two corrected fixtures both end at eight because they both contain six actual records. Their intermediate positions differ. That makes the append arithmetic visible even if an eventual report gets the correct final count by accident. In a write procedure verify the exact intervals used by each group, so one overcount and one undercount cannot hide behind a final equal total. In this lesson we can examine the plan without applying an edit to the worksheet.
Close the experiment in a known state
Restore the original practice inputs. Make sure the intentionally faulty comparison and increment have both been replaced. Toggle off the temporary breakpoints or remove the watch you added to this exercise, then run the repaired version without stepping. The latest output should agree with the known small test. The workbook's source inputs remain unchanged from your restored fixture. Keep a diagnostic note or save the repaired practice workbook if it is useful for review.
If you are studying the code without execution, mark each expected value as predicted and use the pair of before-and-after calculations for the verification. It is possible to prove the arithmetic on paper while still leaving native workbook interaction untested. State that distinction in your handoff. Keep the bad and repaired traces under different labels. Someone reading an Immediate window with both sets of lines should be able to tell which three numbers belong to each run. Add the input order and exact comparison in your notes, so the next learner can repeat either case from the same fixture.
Quick checks
Read the line and the state separately
What does the highlighted next statement tell you?
It identifies the instruction VBA will execute next from this pause. If it is the final write, the value can already be present in a variable while the worksheet still holds the earlier data. Step once and inspect both the next line and the destination.
What is visible when you step into IsPastCutoff?
You can inspect the helper's current parameters, elapsed and limit. On the first fixture row both equal 15. Evaluating greater than or equal gives True, while strict greater gives False. That evidence locates the defect inside the helper.
How do Step Into and Step Over differ on a call?
Step Into lets you observe the called procedure's statements. Step Over runs that call as a unit then pauses at the next instruction in the caller when nothing else interrupts it. Both execute code. Choose according to whether you need to inspect the callee's behavior or the caller's surrounding state.
How many rows does the header-only group consume?
It consumes zero data rows. Its source count includes one header, so subtract one. If the next destination position is eight before the group, it remains eight. That is an effective check against accidentally advancing by the source height including its header.
Which editor panel would you use to read the current local counter?
Use the Locals window while paused in its procedure. An Immediate read-only expression can also show its value in the current context. After the run has finished, the printed trace gives evidence about what happened even though the ordinary local variables are no longer in scope.
Can Reset reverse an earlier worksheet write?
It ends the paused execution. It does not roll back worksheet effects that already happened and can bypass the normal exit path. Use a disposable workbook and inspect the actual cell changes. Next time place the breakpoint before the write if you only need the in-memory state.
Interview and discussion
Use a concrete before-and-after example
How would you locate a logical defect in a macro that compiles?
Decide the expected result on a known tiny fixture, then pause at the first statement likely to choose that result. Inspect input values and step through the decision. In the example 15 at the cutoff exposes a condition that is inclusive instead of strict. Correct the smallest cause and rerun the exact tests.
What makes a read-only Immediate expression useful?
It can reveal a value or a comparison in the current execution context without modifying the source cells or assignments. The two expressions in the timing lab distinguish two rules using the same operands. Avoid expressions that call an action or change a variable if you want a clean comparison.
Why track the record ID along with a row number?
The row number describes the current position, which can change after sorting or editing the report. The ID tells you which decision belongs to which source record. Recording both allows another developer to reproduce the issue on a known fixture and recognize when the layout or ordering has changed.
How do you show that an append plan uses only record counts?
Test groups with four, two and zero actual records. Starting at two, the planned next positions should be six, eight and eight. Inspect the Local values before the increment and use the source heights to locate the included header. In a separate output exercise match actual IDs and verify the end range.
What should a good debugging handoff include?
Identify the workbook, worksheet, procedure, exact fixture and relevant state before the selected line. Record the expected outcome, observed defect and corrected one-line behavior. State what was checked after the repair, including a neighboring cell or source record that the action should leave intact. Tell a teammate whether the evidence was observed in desktop Excel or traced manually.
Six recall cards
- Pause before effect
The next-statement marker means the highlighted line is still to execute. Check values before and after one step.
- Choose your depth
Step Into enters a helper. Step Over executes the call as a unit. Step Out finishes the current procedure.
- Inspect current scope
Locals shows the active procedure's variables. Immediate can show diagnostics from several runs, so identify the current one.
- Prove exact equality
15 is not greater than 15. A practice value exactly at the cutoff reveals the wrong comparison.
- Exclude repeated headers
Four, two and zero records from start row two give next positions six, eight and eight.
- Trace independently
Use a small fixture and a separate calculation. Test both the changed output and the unrelated data that stays.
Microsoft references
Continue practising: explore the existing Excel Task Hub for additional exercises.