To cancel a running Excel VBA loop on Windows, press Ctrl+Break; Esc may also work, especially when the code calls DoEvents. For a loop that needs to exit cleanly, enable VBA’s interrupt handling and use an error handler to catch the cancellation, then restore application settings and tidy up.
If Excel seems busy, it may take a moment to respond. The key practical distinction is between interrupting a macro immediately and asking it to stop in a controlled way. A controlled exit gives your code a chance to reset the status bar, close files, or restore settings before it ends.
What happens when you interrupt a VBA loop
A VBA loop runs on Excel’s main thread. While it is doing work, Excel may not respond to clicks or repaint the window promptly. An interrupt asks VBA to stop executing. Excel can then display an interruption message or pass the interrupt to an error handler, depending on the macro’s settings.
In ordinary Excel VBA, Application.EnableCancelKey is set to xlInterrupt by default. With that setting, pressing an interrupt key stops the macro and typically shows a message explaining that execution was interrupted. You can choose xlErrorHandler instead to route the interruption into VBA error handling. The corresponding error number is 18.
Stopping a macro is not the same as undoing its work. Excel’s Ctrl+Z undo history does not reverse changes made by VBA, and an abrupt interruption can leave partly updated cells or settings. If a macro edits a workbook, save a copy before running it.
Try the keyboard shortcut first
On Windows, press Ctrl+Break while the macro is running. Some keyboards label the key Pause, Break, or Pause/Break; on compact keyboards it may require an Fn combination. If the shortcut does not appear to work immediately, give Excel a few seconds to process it rather than repeatedly pressing keys or closing the application.
Esc can also interrupt some running VBA procedures, but its responsiveness depends on what the code is doing. A long, tight loop that never yields control can make Excel slow to notice a key press. Adding periodic calls to DoEvents gives Excel an opportunity to process pending input and refresh its interface. It does not guarantee that every macro can be stopped instantly.
If Excel is displaying a VBA error or interruption dialog, read it before choosing an option. Selecting End stops execution abruptly; selecting Debug opens the VBA editor at the point where execution stopped. Debug is useful when you want to inspect a problem, but it is not a normal way to cancel and clean up a production macro.
Make a long loop responsive with DoEvents
DoEvents temporarily yields execution so Windows and Excel can process queued events. It is often useful in a lengthy loop, but calling it on every iteration can add overhead. A common approach is to call it every few hundred or thousand iterations, choosing an interval appropriate to the work being done. If each iteration takes a long time, use a shorter interval or provide another cancellation check.
Yielding control has a trade-off: users may interact with Excel while the macro is paused. That can trigger worksheet events or allow another action to start code that changes the same data. For sensitive macros, consider disabling relevant controls or adding a guard that prevents a second run. Avoid treating DoEvents as a substitute for a deliberate cancellation plan.
A progress indicator can make a long operation easier to understand. For example, a macro can update Application.StatusBar every so often and reset it to False when finished. Progress updates should be occasional rather than performed on every loop pass, because frequent screen updates can slow processing.
Use an error handler for a clean cancellation
For a macro that should catch the user’s interrupt and run cleanup code, set Application.EnableCancelKey to xlErrorHandler. The following example processes a simple calculation, updates the status bar, and checks for interruption. It does not change worksheet cells, so it illustrates the cancellation pattern without modifying workbook data.
Save a copy of the workbook before running any macro that changes data: VBA changes cannot be undone with Ctrl+Z. To try this example, open the Visual Basic Editor, insert a standard module, and run the procedure. On Windows, Alt+F11 opens or closes the editor; on Mac, the editor shortcut can vary with keyboard settings, and the Visual Basic Editor is available from Excel’s Tools menu.
Sub LongLoopWithCancel()
Dim i As Long
Dim total As Double
Dim cancelled As Boolean
On Error GoTo HandleError
Application.EnableCancelKey = xlErrorHandler
For i = 1 To 1000000
total = total + i
If i Mod 1000 = 0 Then
Application.StatusBar = "Processing " & Format$(i / 1000000, "0%")
DoEvents
End If
Next i
GoTo CleanUp
HandleError:
If Err.Number = 18 Then
cancelled = True
Err.Clear
Else
MsgBox "Macro error " & Err.Number & ": " & Err.Description, vbExclamation
End If
Resume CleanUp
CleanUp:
Application.StatusBar = False
Application.EnableCancelKey = xlInterrupt
If cancelled Then
MsgBox "The loop was cancelled.", vbInformation
End If
End Sub
When an interrupt raises error 18, the handler records that the user cancelled and continues to the cleanup section. Other errors display their number and description before cleanup runs. The cleanup resets the status bar and returns the cancel-key setting to xlInterrupt. Excel also resets this setting when it returns to an idle state, but explicitly restoring it makes the procedure’s intent clear.
Common reasons cancellation seems not to work
- The loop does not yield: A tight loop can delay Excel’s response. Add periodic
DoEventscalls or another deliberate check point. - The shortcut is different on the keyboard: Check whether Break is combined with another key, such as Fn. The key label and layout vary by keyboard.
- Cancellation is disabled: If code set
Application.EnableCancelKey = xlDisabled, Excel will not accept the normal user interrupt while that setting is active. Avoid disabling it for long-running work unless there is a specific, carefully managed reason. - The macro is waiting on another operation: A blocked external call, calculation, or other lengthy task may not respond as promptly as a simple VBA loop.
- The code stopped at an error dialog: Read the message and choose whether to end or debug. An error dialog can make it seem as though the shortcut did nothing.
- Excel has not finished handling the request: A very busy workbook can take time to respond. Force-quitting Excel risks losing unsaved work and can leave external operations incomplete.
Another tempting option is the VBA End statement. It terminates all running VBA code immediately rather than following a normal cleanup path. That can leave application settings changed or a workbook only partly updated. It is generally safer to use an interrupt handler or a cancellation flag that lets the procedure exit at a known point.
Choose between interrupting and checking a cancel flag
Keyboard interruption is convenient when a person is watching the macro and needs to stop it now. A cancel flag is more appropriate when a macro has a planned stopping point, such as after finishing the current record. The flag can be set by a button on a UserForm or by another controlled part of the program, then checked between units of work.
For example, a batch process could check a Boolean variable before starting each row. If the variable indicates cancellation, it can leave the loop, close any resources it opened, and report how many rows were completed. This is different from interrupting in the middle of a cell update, where the workbook may be left in a partial state. The best choice depends on whether immediate stopping or predictable cleanup matters more.
For a short loop that only reads values, the default interrupt behavior may be sufficient. For a long operation that writes data, updates application-wide settings, or communicates with another program, plan the cleanup first. Keep the amount of work between cancellation checks small enough that the user does not have to wait unreasonably long.
Excel for Mac and Excel for the web
Excel for Mac supports VBA, but keyboard shortcuts and key labels differ from Windows. On Mac, Command+Period is commonly used to interrupt a running macro; the exact behavior may depend on the keyboard and Excel version. If a keyboard shortcut is unavailable, use the Excel or Visual Basic Editor controls that are available in that version, and keep a saved copy before stopping a macro that modifies data.
Excel for the web does not run VBA macros. A workbook containing VBA can be opened there, but the VBA procedure must be run in the desktop Excel application. If the goal is to automate a workbook in a browser, Office Scripts or another supported automation option may be more appropriate; these are separate from VBA and use a different programming model.
Frequently Asked Questions
How do I stop a VBA macro that is stuck in a loop?
On Windows, press Ctrl+Break and wait for Excel to respond. If the loop calls DoEvents periodically, Esc may also be processed. If the macro is changing important data, be aware that stopping it does not undo completed changes.
Why does Ctrl+Break not stop my Excel macro?
The keyboard may require an Fn combination, or the code may be busy without yielding control. Check that cancellation has not been disabled with Application.EnableCancelKey = xlDisabled. A long-running loop can also be made more responsive by adding periodic DoEvents calls.
Can I cancel a VBA loop without closing Excel?
Usually, yes. Use the interrupt shortcut and let Excel handle the stop. If the procedure has an error handler for error 18, it can catch the interrupt and run cleanup. Closing Excel should be a last resort because unsaved changes may be lost.
What does error 18 mean in VBA?
Error 18 is the VBA error raised for a user interrupt when cancellation is directed to an error handler. A procedure can test Err.Number for 18, treat it as cancellation, and handle other errors separately.
Does Ctrl+Z undo a cancelled macro?
No. Excel’s ordinary undo command does not reverse changes made by VBA. Save a backup before running a macro that edits a workbook, and design the procedure to save or restore data deliberately if that is required.
Can I stop a VBA macro in Excel for the web?
No. Excel for the web does not execute VBA macros. Run the macro in desktop Excel, or consider a supported browser-based automation tool such as Office Scripts instead.
Related
- Excel Split Cell at a Specific Character?
- Excel Slicers for Multiple PivotTables: How to Connect
- Excel Named Ranges in Data Validation: How to Use Them
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA String to Number: Safe Conversion MethodsIn Excel VBA, convert text that represents a number with a conversion function such as CDbl for decimals…
- Replace Excel Macros? Alternatives and When to SwitchYes—many Excel macros can be replaced, but the right substitute depends on the task: use formulas for calculations,…
- Excel VBA: Add Days to a Date in Excel Cells and MacrosTo add days to a date in Excel VBA, use DateAdd("d", numberOfDays, dateValue) or add a whole number…
- Microsoft VBA for Excel: What It Is and How It WorksMicrosoft VBA for Excel is the programming language built into desktop Excel for automating repetitive tasks, creating custom…
- Excel VBA Scroll Bar Form Control: Setup, Uses, and CodeIn Excel for Microsoft 365 on Windows, insert a Form Control scroll bar from Developer > Insert >…
- Excel VBA UserForm Coding: Build a Data-Entry FormExcel VBA UserForm coding means creating a custom dialog in Visual Basic for Applications and writing code that…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.