Ravindra BagaleCourses & study guides

12. Macros and VBA

12.15 Debugging: F8, Breakpoints, Immediate and Locals Windows

Tool How Use
Step Into F8 Run one line at a time; the yellow line is the next to run
Breakpoint click the grey margin or F9 Run (F5) until that line, then pause
Run to cursor Ctrl + F8 Run until the cursor line
Hover point at a variable while paused See its value
Immediate window Ctrl + G Debug.Print output; type ?r or ?Cells(r,3).Value while paused
Locals window View › Locals Window All variables and their current values
Watch right-click a variable › Add Watch Break when a value changes or becomes True
Compile Debug › Compile VBAProject Finds syntax and undeclared-variable errors before running
Reset the square Stop button Stop a paused macro

Worked example. CombineCitySheets copies one row too few. Raja sets a breakpoint on destRow = destRow + (lastRow - 1), presses F5, then F8 through two sheets while watching lastRow and destRow in the Locals window – and finds the header row was counted twice in his modified version.

Ravindra Bagale's Tip

When a macro goes wrong, many students sit reading the code and guessing. Instead, run it one line at a time with F8 and watch the variables in the Locals window – you'll see immediately where it went wrong. Before running, do Debug › Compile; spelling mistakes are caught right there.

Practice task

Put a breakpoint inside the For loop of LoopExamples, step with F8, and print r and Cells(r, 8).Value in the Immediate window at each step.