Please Note: This article is written for users of the following Microsoft Excel versions: 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365. If you are using an earlier version (Excel 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Excel, click here: Aborting a Macro and Retaining Control.

Aborting a Macro and Retaining Control

Written by Allen Wyatt (last updated November 28, 2024)
This tip applies to Excel 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365


6

When you are developing a macro for others to use, you may want to add a method for the user to exit your macro before it ends, and still retain control of what the macro does. Ctrl+Break will stop a macro, but it doesn't exit gracefully, as it allows the user to view the code in the VBA Editor.

There are several ways you can approach this problem. The first is to build a "do you want to exit" prompt into your macro, and then have the macro display the prompt periodically. For instance, consider the following code:

Do ...

    '    your code goes here

    Counter = Counter + 1
    If Counter Mod 25 = 0 Then
        If MsgBox("Stop Macro?", vbYesNo) = vbYes Then End
    End If
Loop

The macro construction is based on the premise that you have a series of steps you want to repeat over and over again, through the use of a Do ... Loop structure. Every time through the loop, the value of Counter is incremented. Every 25 times through the loop, the "stop macro?" prompt is displayed, and the user has a chance to exit.

This approach is easy to implement and may work quite well for some purposes. The biggest drawback to this approach, however, is that it doesn't allow immediacy—the user must wait to exit the macro until at least 25 iterations have occurred.

Another approach is to "hide" the VBA code and apply a password to it. You do this by following these steps from within the VBA Editor:

  1. Choose the VBAProject Properties option from the Tools menu. The editor displays the Project Properties dialog.
  2. Make sure the Protection tab is displayed. (See Figure 1.)
  3. Figure 1. The Protection tab of the Project Properties dialog box.

  4. Choose the Lock Project for Viewing check box.
  5. In the Password box, enter a password you want used to protect the macro.
  6. In the Confirm Password box, enter the same password a second time.
  7. Click OK.

Close the VBA Editor, then save the workbook. With the VBA project protected, the user can still click Ctrl+Break to stop the macro, but they won't be able to get to the actual program code. They will only be able to choose from the Continue or End buttons, both of which protect your code. As an added benefit, this approach also restricts the user from viewing your code by using menu, toolbar, or ribbon choices.

Perhaps the best approach, however, is to create an error handler that will essentially take charge whenever the user presses Esc or Ctrl+Break. The handler that is run can then ask the user if they really want to quit, and then shut down gracefully if they do. Here's some example code that shows how this is done:

Sub Looptest()
    Application.EnableCancelKey = xlErrorHandler
    On Error GoTo ErrHandler

    Dim x As Long
    Dim y As Long
    Dim lContinue As Long

    y = 100000000
    For x = 1 To y Step 1
    Next

    Application.EnableCancelKey = xlInterrupt
    Exit Sub

ErrHandler:
    If Err.Number = 18 Then
        lContinue = MsgBox(prompt:=Format(x / y, "0.0%") & _
          " complete" & vbCrLf & _
          "Do you want to Continue (YES)?" & vbCrLf & _
          "Do you want to QUIT? [Click NO]", _
          Buttons:=vbYesNo)
        If lContinue = vbYes Then
            Resume
        Else
            Application.EnableCancelKey = xlInterrupt
            MsgBox ("Program ended at your request")
            Exit Sub
        End If
    End If

    Application.EnableCancelKey = xlInterrupt
End Sub

Notice that this example uses the EnableCancelKey method, assigning it the name of the label that should be jumped to if the cancel key (Esc or Ctrl+Break) is pressed. In this case, ErrHandler is jumped to, and the user is asked what to do. If the user chooses to exit, then the macro is shut down gracefully.

Notice that the first thing done after the ErrHandler label is to check if the Number property of the Err object is equal to 18. If it is, you know that a cancel key was pressed. If not, then some other type of error occurred, and it should be handled in whatever way is appropriate for your macro.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (139) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Microsoft 365. You can find a version of this tip for the older menu interface of Excel here: Aborting a Macro and Retaining Control.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Converting PDF to Word Documents

One way that documents are commonly shared with others is in the form of a PDF file. Getting information from a PDF file ...

Discover More

Determining the Number of Bookmarks Defined in a Document

If you develop a macro that needs to work with bookmarks defined in a document, it is inevitable that you will need a way ...

Discover More

Pasting Leading Zeroes

Paste information into a worksheet, and you may be surprised to see leading zeroes disappear before your eyes. Here's how ...

Discover More

Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!

More ExcelTips (ribbon)

Checking the Scope of a Defined Name

When creating a macro to work with the names of defined ranges, you may need to know whether the scope of the name is for ...

Discover More

Conditionally Displaying a Message Box

You can, from within your macros, easily display a message box containing a message of your choice. If you want to ...

Discover More

Default Worksheet when Opening

When opening a workbook, you may want to make sure that a particular worksheet is always displayed first. The only way to ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 2 + 2?

2024-11-30 11:15:28

J. Woolley

@Brian
GetKeyState is one of many Windows API (Application Programming Interface) functions. My Excel Toolbox references several in its M_WinAPI module, which is declared Private (only available within MyToolbox.xlam).
Here's another way to "wait for the user to select a cell or to cancel."

    Dim msg As String, rSele As Range
    msg = "Select a cell, then click OK. Otherwise, click Cancel." _
        & vbLf & "(Note: Enter = OK, Escape = Cancel.)"
    Set rSele = Nothing
    On Error Resume Next
        Set rSele = Application.InputBox(Prompt:=msg, _
            Default:=ActiveCell.Address, Type:=8)
    On Error GoTo 0
    If rSele Is Nothing Then
        MsgBox "You clicked Cancel or pressed Escape"
    Else
        rSele.Select
        MsgBox "You selected " & rSele.Address
    End If

See https://sites.google.com/view/MyExcelToolbox/


2024-11-30 04:33:44

Brian

@J.Woolley
Thanks - that works brilliantly in my application. My loop is only DoEvents as I need it to wait for the user to select a cell or to cancel. The more I use Excel the more I realise how much I don't know about it - especially the user32 library.


2024-11-29 11:53:18

J. Woolley

@Brian
The Tip's Looptest macro has several issues:
1. It runs too fast for a reasonable test.
2. It needs VBA's DoEvents function to register keyboard input.
3. Windows will interrupt with Ctrl+Break but not Escape.
Here's an alternate version that quits when you press Escape:

Private Declare PtrSafe Function GetKeyState Lib "user32" _
    (ByVal nVirtKey As Long) As Integer

Sub Looptest2()
    Dim x As Long, y As Long
    y = 100000000
    For x = 1 To y Step 1
        DoEvents
        If GetKeyState(&H1B) < 0 Then
            MsgBox Format(x / y, "0.0%") & " complete" _
                & vbLf & "You pressed ESC"
            Exit Sub
        End If
    Next
End Sub


2024-11-28 11:17:48

Brian

Probably me, but I can't get the error handler method to trigger when I press Esc. It works on break (ctrl+fn+b on my dell Inspiron) but not with esc, Fn+esc, Ctril+Esc, or Ctrl+Fn+esc. I have a do loop that just does doevents until the user changes the selection cell and I have a made one cell the cancel one - works but a bit clunky. The break sequence is a work around but I'd really like to be able to just hit esc. Any thoughts?


2021-01-11 05:58:54

Barry

IMHO, using Ctrl+Break will never cause a "clean" break in program execution, except for the simplest of macros. It is likely that here are several lines of code in the main loop of the macro, and there is a high probability that the Ctrl+Break will be actioned during the execution of this code. Therefore the some lines of code will have been executed and others will not have been executed in the pass through this code when the Ctrl+Break occurs, this will leave the data in an unknown state which is not desirable nor good programming practice.

A better way would be to have button control on the visible worksheet or a modeless Userform which when clicked would set a flag which the main macro tests at the end of each pass through the loop, together with a DoEvents instruction to allow the user the opportunity to click the "Stop" button. I would also recommend disabling the Ctrl+Break function during the execution of the code (and re-enabling at the end of course) to prevent interruption in this way. These extra lines of code will slow the macro down a bit but are worthwhile to ensure things don't get messed up.
An alternate way to set the flag is to invoke the flag setting macro from a custom button in the ribbon, a keyboard shortcut could be set or QAT. The Ctrl+Break/error handler method could also be modified so that the code would "Resume" the completion of the current pass before then exiting the loop.


2021-01-10 16:06:06

Bob Williams

I found the "Aborting a Macro and Retaining Control" tip quite useful. Thanks!
Your articles are always clear and concise and complete. This one could be made more complete by including a reference to the err numbers and their meanings.
Thanks again,
Bob Williams


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.