top of page

You are learning Macros in MS Excel

How to debug a macro step-by-step using breakpoints in VBA?

Here's how to debug a macro step-by-step using breakpoints in VBA:

1. Access the VBA Editor:

- Open your Excel workbook with the macro you want to debug.
- Press `Alt` + `F11` to launch the Visual Basic Editor (VBE).

2. Identify the Macro Code:

- In the Project Explorer window (usually on the left side), navigate to your VBA project (usually named "VBAProject").
- Expand the project tree and locate the specific VBA module containing the macro you want to debug.
- Double-click the module name to open the VBA code in the editing window.

3. Set Breakpoints:

- Place your cursor on the line of code where you want execution to pause.
- There are three ways to set a breakpoint:
- Press `F9` (shortcut key).
- Click on the gray margin to the left of the line number.
- Go to the "Debug" menu and choose "Toggle Breakpoint."
The line with the breakpoint will be highlighted with a red dot in the margin.

4. Run the Macro with Debugging:

- There are two ways to initiate debugging:
- Click the yellow "Run Sub/UserForm" button (looks like a play button) on the VBA toolbar.
- Go to the "Debug" menu and choose "Run Sub/UserForm."

5. Step Through the Code:

- When the macro encounters a breakpoint, execution will halt.
- Use the following buttons on the VBA toolbar to navigate through the code step-by-step:
- F8 (Step Into): Executes the current line and then steps into any function calls within that line.
- F11 (Step Over): Executes the current line but skips over any function calls, treating them as a single step.
- Shift + F11 (Step Out): Executes the remaining code within the current function and then exits the function, continuing execution at the next line in the calling code.
- Ctrl + F9 (Continue): Resumes normal macro execution, running the remaining code without pausing.

6. Inspect Variables (Optional):

- While paused at a breakpoint, you can hover over variables in the code window to see their current values in a tooltip.
- The "Locals" window (usually located at the bottom of the VBE) displays the values of all variables in scope at the current point in the code. You can double-click on a variable to modify its value during debugging.

7. Remove Breakpoints:

- Once you're finished debugging a specific line, you can remove the breakpoint by clicking on the red dot again or pressing `F9`.
- To remove all breakpoints in your code, use the shortcut `Ctrl` + `Shift` + `F9`.

8. Conclusion:

By using breakpoints and the debugging tools in the VBE, you can systematically examine your macro's execution, identify errors, and ensure it functions as intended.

bottom of page