Stopping Excel Macro executution when pressing Esc won't work

ptpaterson picture ptpaterson · Jul 21, 2011 · Viewed 261.7k times · Source

I'm running excel 2007 on XP.

Is there a way to stop a macro from running during its execution other than pressing escape? Usually if I think I created an infinate loop or otherwise messed something up I hit escape and it throws an error but the macro stops.

This time (and I've done it before but not this badly), I set up a msgbox for some quick debugging. Turns out it had to loop about 6000 times, which made means I had to "OK" 6000 message boxes, which took several minutes. I didn't save before running (another mistake) so I couldn't open task manager to exit.

Is there another way to stop the execution of a macro in case I goof up like this again?

Answer

Tomalak picture Tomalak · Jul 21, 2011

Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.

Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.

You can even edit most of the code while it is running.

Use Debug.Print to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox.

Use breakpoints or the Stop keyword to automatically halt execution in interesting areas.

You can use Debug.Assert to halt execution conditionally.