Excel VBA: How to Cancel a UserForm

VBA & macros · Updated November 21, 2026

To cancel an Excel VBA UserForm, handle a Cancel button by setting a cancellation flag and hiding the form; handle the title-bar X in UserForm_QueryClose if you also need to record that choice. Use Hide when the calling macro still needs to read the form’s values, and use Unload when you are finished with the form.

What “cancel” means in a UserForm

Canceling a form can mean two different things: closing the window, or telling the macro that the user rejected the operation. Closing a window alone does not necessarily tell your code which choice the user made. A dependable form records that decision explicitly, then returns control to the procedure that displayed it.

For example, a data-entry form might have an OK button and a Cancel button. If the user chooses OK, the macro should validate and use the entered values. If the user chooses Cancel—or closes the form with the X—the macro should stop the operation without treating incomplete entries as accepted. That distinction is especially important if the next step writes data to a worksheet or changes workbook settings.

A UserForm is modal by default when displayed with .Show: the user must dismiss it before interacting with the workbook. When the form is hidden or unloaded, the code after .Show continues. This pause-and-return behavior makes a modal form convenient for collecting a choice, provided the form communicates that choice clearly.

Add a Cancel button and support Esc

In the Visual Basic Editor, add a CommandButton to the form and give it a meaningful name, such as cmdCancel. In the Properties window, set its Caption to Cancel and its Cancel property to True. That property makes the button respond when the user presses Esc; it does not run cancellation code by itself. The button’s click event still needs to hide the form and set a result.

For an OK button, set the CommandButton’s Default property to True if you want Enter to activate it. Make sure the form’s focus and validation behavior remain sensible: an Enter keypress should not accept an invalid or blank entry simply because the OK button is the default.

In the form’s code module, the Cancel button can use this basic pattern:

Private Sub cmdCancel_Click()
    WasCancelled = True
    Me.Hide
End Sub

This example assumes the form has a public Boolean variable named WasCancelled, declared in its code module. The form hides rather than unloads so the calling procedure can inspect that variable. If the form only needs to close and no later code needs its contents or result, Unload Me is also a valid way to close it, but it is not interchangeable with hiding when you need to retrieve state afterward.

Record whether the user accepted or canceled

A useful pattern is to make the form return a clear result. Declare a public variable near the top of the UserForm module, below Option Explicit:

Option Explicit

Public WasCancelled As Boolean

Set the result in both button handlers. For instance, an OK handler might check a text box named txtName, then mark the operation accepted and hide the form:

Private Sub cmdOK_Click()
    If Len(Trim$(Me.txtName.Value)) = 0 Then
        Me.txtName.SetFocus
        Exit Sub
    End If

    WasCancelled = False
    Me.Hide
End Sub

The blank-name check is only an example; replace it with the validation your form actually needs. Because the Cancel handler sets WasCancelled to True and the OK handler sets it to False, the caller can distinguish the two outcomes. Set the initial value before every display rather than assuming a hidden form has been freshly initialized. UserForm_Initialize runs when the form is first loaded, not every time a previously hidden instance is shown again.

Handle the title-bar X with QueryClose

The X in the form’s title bar does not click your Cancel button. If the caller must treat that action as cancellation, handle the form’s QueryClose event. This event supplies a CloseMode value describing how the close was requested and a Cancel argument that can prevent the close.

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = vbFormControlMenu Then
        Cancel = True
        WasCancelled = True
        Me.Hide
    End If
End Sub

With this handler, choosing the title-bar X marks the operation canceled and hides the form instead of unloading it. The caller can then read WasCancelled. The condition matters: code can also close a form with Unload, and that close has a different mode. Do not block every close indiscriminately, or your own cleanup code may be unable to unload the form.

If you do not care whether the user clicked Cancel or the X, you can allow the X to close the form normally and handle the result another way. But be deliberate: without a result flag or a defined close policy, the calling code can mistake a dismissal for acceptance or read a value that was never confirmed.

Hide versus Unload

Me.Hide removes the form from view but keeps that loaded instance and its controls in memory. Code can read its text boxes, option buttons, or result variables after .Show returns. The form can also be shown again, so reset its controls and cancellation result at the start of each new operation.

Unload Me closes and removes the form instance. It is appropriate when the form is done and its values have already been copied somewhere safe. Unloading a form can reset its controls when it is loaded again, so do not unload it before the caller has retrieved information it needs. A common safe sequence is to hide the form, inspect or copy its values in the calling procedure, and then unload it.

  • Choose Hide when the caller needs to inspect the form after it closes.
  • Choose Unload when the form and its controls are no longer needed.
  • Use an explicit result variable or property when later code must know whether the user accepted or canceled.

These methods are about the form’s lifetime, not about rolling back worksheet changes. If code changes cells before the user confirms, hiding or unloading the form will not reverse those edits. Delay committing changes until after confirmation, or write code that deliberately restores the prior values.

Call the form and check the result

Before running a macro that changes a workbook, save a copy of the workbook. VBA macros cannot be undone with Ctrl+Z. The following calling procedure assumes a UserForm named frmEntry with the public variable, buttons, and text box described above. It loads the form, displays it, checks the result, and unloads it after reading the value.

Public Sub ShowEntryForm()
    Dim cancelled As Boolean
    Dim enteredName As String

    Load frmEntry
    frmEntry.WasCancelled = True
    frmEntry.Show

    cancelled = frmEntry.WasCancelled
    If Not cancelled Then
        enteredName = CStr(frmEntry.txtName.Value)
        MsgBox "Accepted: " & enteredName
    Else
        MsgBox "Entry canceled."
    End If

    Unload frmEntry
End Sub

Setting the result to True before displaying the form makes cancellation the safe default. If the user closes the form by the X, the QueryClose handler leaves that result True. Only the OK handler changes it to False. Copying the accepted text into a local variable before unloading also makes the order of operations explicit.

The names in the code must match the actual form and controls. In the Visual Basic Editor, open it with Alt+F11 on Windows, or use the Visual Basic command in Excel’s Developer tab. On Mac, the keyboard shortcut can depend on the keyboard and function-key settings; the Developer tab’s Visual Basic command is another route. Excel for the web does not run VBA UserForms, so use desktop Excel for this workflow.

Common cancellation problems

  • The X closes the form but the macro does not know why. Add a UserForm_QueryClose handler or define a deliberate default result. The Cancel button’s click event does not handle the title-bar X.
  • Esc appears to do nothing. Check that a CommandButton on the form has its Cancel property set to True, and that its click event contains the cancellation logic.
  • The form reports the previous result. A hidden form can be reused without running its Initialize event again. Reset the result immediately before each .Show.
  • The caller cannot read the controls. Check whether the form was unloaded before the caller read them. Hide it first, copy the values, and unload afterward.
  • Cancel appears to undo worksheet edits. It does not. Cancellation only changes what your VBA code does next; it cannot reverse earlier edits automatically.

For debugging, place a breakpoint in the button event and in UserForm_QueryClose, then run the form from desktop Excel. If the code does not compile, check that the event procedure name matches the control’s actual (Name) property and that the form module contains the result variable. Keep workbook changes behind the acceptance check so that an early cancellation cannot leave partial results.

Frequently Asked Questions

How do I close a UserForm in Excel VBA?
Use Me.Hide to dismiss it while keeping the form instance available, or Unload Me to remove it. If a calling macro needs the entered values, hide the form, read or copy them, and unload only afterward.

How do I make Esc cancel an Excel UserForm?
Set the Cancel button’s Cancel property to True in the Properties window. Pressing Esc then activates that button, so its click event must set the cancellation result and hide or unload the form.

Does clicking the X run the Cancel button’s code?
No. The title-bar X raises the form’s UserForm_QueryClose event, not the Cancel button’s click event. Handle that event if closing with the X should count as a canceled operation.

Should I use Hide or Unload when canceling?
Use Hide if the caller needs to read the result or controls after the form closes. Use Unload when the form is finished and nothing on that instance needs to be read. For either choice, make the cancellation outcome explicit.

Can I run a VBA UserForm in Excel for the web?
No. Excel for the web does not run VBA macros or UserForms. Open the workbook in desktop Excel; on Mac, use the desktop application and check its Developer tab or keyboard settings for the Visual Basic Editor.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.