At this point you should know that you can run a subroutine quickly by pressing F5, or step through it slowly by pressing F8. What if you want to do both in different parts of the same procedure? The answer is: use a breakpoint!
When your code hits a breakpoint it will pause and allow you to step through the procedure from that line.
You can click here to download the sample code used in this part of the lesson.
You can click here to download a file containing the sample code.
Setting a Breakpoint
To set a breakpoint, click somewhere on the line of code on which you'd like it to appear:
You don't need to select the entire line, just click somewhere on it.
You can then choose an option from the table below:
|Debug | Toggle Breakpoint||F9|
The line of code will clearly indicate that a breakpoint has been assigned to it:
Breakpoints appear as shown here.
You can disable the breakpoint using any of the methods you used to enable it. Perhaps the easiest way to toggle a breakpoint on a line is to click in the grey bar to the left of the code window:
You can click on an existing breakpoint to disable it. Click in the same place to switch it back on.
Running Code Containing Breakpoints
Once you've set a breakpoint, you can begin a procedure in the normal way by pressing F5 or choosing Run | Run Sub/UserForm from the menu:
Your code will run as quickly as it can and pause when it reaches a line containing a breakpoint.
Once your code has paused you can use the F8 key to begin stepping through the procedure from that point. At any stage you can press F5 to continue running the procedure quickly, or choose Run | Reset to end it.
Using Multiple Breakpoints
In a long procedure it can be useful to have multiple breakpoints. You can set as many breakpoints in a procedure as you like:
Use any of the methods described earlier to set a breakpoint on any line of code.
You can now run the subroutine in stages. Press F5 once to reach the first breakpoint:
You can now check that everything has worked as expected up to this point.
Press F5 again to reach the next breakpoint:
Again, you can check that everything has worked as expected up to this point.
Press F5 once more to reach the end of the procedure.
You can remove breakpoints individually using any of the techniques described earlier. You can also remove all of the breakpoints at once by choosing one of the options from the table below:
|Debug | Clear All Breakpoints||Ctrl + Shift + F9|
All breakpoints will be removed automatically when you close the workbook in which the code is saved.
You can continue to experiment with setting and removing breakpoints using the sample code provided. When you're ready you can move to the next part of the lesson.