To close an Excel VBA UserForm when a button is clicked, put Me.Hide in that button’s Click event to hide the form, or use Unload Me to close and unload it. For a button that should simply dismiss the form, Unload Me is usually the clearest choice; use Me.Hide when you want to preserve the form’s current values and state.
Put the code in the button’s Click event
A UserForm button responds to its Click event. The event procedure belongs in the code module for the UserForm itself, not in a worksheet code module or a standard module. In the Visual Basic Editor, open the form, double-click the button, and Excel will create an event procedure for that control. Its name includes the button’s control name, such as cmdClose_Click.
For a button named cmdClose, this is the simplest close handler:
Private Sub cmdClose_Click()
' Close this UserForm and release its loaded instance.
Unload Me
End Sub
Me refers to the UserForm whose code is running. This means the code does not depend on the form’s public name, and it is convenient if you later rename the form. For a button named differently, use the event procedure Excel generates for that button rather than copying the procedure name unchanged.
Choose between hiding and unloading
Both methods make the form disappear, but they do not mean the same thing. Me.Hide changes the form’s visibility while leaving it loaded in memory. The form’s controls retain their current values, and code that opened the form can inspect those values after the form is hidden. A later call to show the same loaded form can display that state again.
Unload Me removes the form from its loaded state. It is appropriate when the user is finished with the form and you do not need to keep its control values for the caller to read afterward. If the form is shown again, it is loaded again; its initialization code can run as part of that process. Do not assume every value you set in code will always be reset automatically, though: code in the form’s initialization or activation events, and the way the form is referenced, can affect what appears on a later display.
- Use
Unload Mefor a straightforward Close, Done, or Cancel button that ends the form session. - Use
Me.Hidewhen the calling procedure needs to read the form’s entries after it closes, or when you intend to show the same form instance again. - Use neither as a substitute for saving or validating data. Closing the form does not automatically write its control values to a worksheet.
One common misconception is that Hide and Unload are interchangeable because both remove the window from view. They are not: hiding preserves a loaded form, while unloading ends its loaded state. That distinction matters particularly when a form collects information that another procedure must use.
Close the form after saving or validating entries
A form often should not close immediately if the user has entered information that must be checked or saved. Put the validation or write operation before the close statement. If a check fails, show a useful message, return focus to the relevant control, and exit the event procedure without hiding or unloading the form.
This example assumes the UserForm contains a TextBox named txtName and a button named cmdSave. It rejects a blank name, writes a valid entry to cell A1 on Sheet1 in the workbook containing the VBA code, and then unloads the form:
Private Sub cmdSave_Click()
Dim enteredName As String
' Check the entry before changing the worksheet.
enteredName = Trim$(Me.txtName.Value)
If Len(enteredName) = 0 Then
MsgBox "Enter a name before saving.", vbExclamation
Me.txtName.SetFocus
Exit Sub
End If
' Save the value, then close the form.
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = enteredName
Unload Me
End Sub
In this example, if the TextBox is empty or contains only spaces, the procedure stops at Exit Sub, so the form remains open. Replace the worksheet name and cell reference with the destination your workbook actually uses. If the code should preserve the values for the caller to process, replace the final Unload Me with Me.Hide and have the calling procedure read the form’s controls before unloading it.
Make sure the button and event procedure match
If clicking the button does nothing, first confirm that the code is in the correct UserForm module and that the procedure name matches the button’s actual control name. A button caption such as “Close” is not necessarily its VBA name; check the button’s (Name) property in the Properties window. The event procedure must use that name followed by _Click.
Also check that the button is enabled and that the form is not in Design Mode in the Visual Basic Editor. If Excel opens the form but the button’s code never runs, a procedure with a similar name in a worksheet or standard module will not handle the button click. A simple test is to add a temporary MsgBox line inside the Click event and see whether it appears when you click the control.
When code outside the form needs to unload it, use the form’s name, for example Unload UserForm1, from a standard module. Inside the form’s own event procedure, Unload Me is generally less error-prone. If you use a separately created form object rather than Excel’s default form instance, make sure you unload the same object that you showed; unloading a different instance will not close the visible one.
Understand modal and modeless forms
By default, calling UserForm1.Show displays a modal form. Excel waits for that form to be hidden or unloaded before the calling procedure continues. This is useful for a short data-entry dialog: the caller can show the form and then act on the user’s decision after the form closes. A button that runs Me.Hide or Unload Me releases that pause.
A modeless form is shown with UserForm1.Show vbModeless. Excel can continue to be used while the form remains open, and the procedure that showed it does not wait for the user to close it. That makes modeless forms behave differently from modal dialogs; do not rely on code after the Show statement as though the user has already finished entering information. The button’s Click event can still hide or unload the form, but the surrounding workflow needs to account for the form being open alongside the workbook.
For a typical confirmation or entry dialog, modal behavior is often simpler. Modeless display is useful when people need to interact with worksheet cells while keeping a tool window visible, but it requires more care about shared data and when changes are committed.
What happens when the user clicks the X
The title-bar X is separate from a command button’s Click event. If you need to respond when the user closes the window that way, the UserForm provides a QueryClose event. Its CloseMode argument indicates the reason for the close request, so code can distinguish a title-bar close from an unload initiated by VBA. A close button using Unload Me does not need a QueryClose handler just to close the form.
To prevent accidental dismissal, handle the appropriate QueryClose case and set its Cancel argument to True when you want to block the close. Be deliberate: preventing the X from working without providing another clear way to exit can trap users in the form. If unsaved entries matter, ask whether the user wants to discard them or save them, and cancel the close request when the user chooses to continue editing.
Find the code and run it safely
In Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor. In Project Explorer, expand the workbook’s Forms folder, open the UserForm, then double-click the relevant button to view or create its Click event. On a Mac, use Excel’s Tools > Macro > Visual Basic Editor menu path; keyboard shortcuts can vary with the Mac keyboard and function-key settings. The VBA event logic is the same, although some controls and features can differ between Windows and Mac.
Save a copy of the workbook before running or changing a macro. VBA changes cannot be undone with Ctrl+Z, and the workbook must be saved in a macro-capable format such as Excel Macro-Enabled Workbook (.xlsm) if you need to retain its VBA project. Excel’s macro security settings may also affect whether the code is allowed to run. Do not enable macros in files from sources you do not trust.
Frequently Asked Questions
What is the VBA code to close a UserForm after a button click?
In the button’s Click event in the UserForm module, use Unload Me to close and unload the form. Use Me.Hide instead if you need the form’s current values to remain available after it disappears.
Should I use Unload Me or Me.Hide?
Use Unload Me when the user is finished and the form does not need to remain loaded. Use Me.Hide when the calling code must inspect the controls or you plan to reuse that loaded form instance.
Why does my UserForm close button do nothing?
Check that the code is in the form’s code module and that the procedure name matches the button’s (Name) property, followed by _Click. Also make sure the control is enabled and that the macro is running rather than being blocked by workbook security settings.
How do I close a UserForm from a regular VBA module?
Use the form’s name, such as Unload UserForm1, when working with Excel’s default instance. If your code created a separate form object, unload that specific object instead. Inside the form’s own button event, use Unload Me.
Can I close a UserForm without losing the entered values?
Yes. Use Me.Hide rather than unloading it, then read the control values from the still-loaded form in the calling code. If you unload the form, copy or save the values first if another procedure will need them.
Related
- Excel Page Break Command: Insert, Move, and Remove
- Excel Page Break Character: Meaning and Print Breaks
- Excel Page Break Dashed Line: What It Means
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel Error 52: Fix Bad File Name or Number in VBAExcel Run-time error 52, “Bad file name or number,” usually means VBA tried to access a file using…
- Excel VBA UserForm Examples: Forms, Code, and Setup GuideCommon Excel VBA UserForm examples include a contact-entry form, a search box, a data-editing dialog, and a task-specific…
- Excel VBA Range Using Cells: Syntax, Examples, and TipsIn Excel VBA, use Cells(row, column) to identify a cell by its row and column numbers, and pass…
- Excel VBA: Copy and Paste Selected Cells with a MacroTo copy selected cells with VBA, call the range’s Copy method and specify a destination cell, as in…
- Simple Macro Recorder and Auto Clicker: How They WorkA simple macro recorder captures a sequence of actions—such as clicks, keystrokes, and pauses—and plays them back; an…
- Excel VBA INDEX: Return Values from a RangeIn Excel VBA, “INDEX” usually means Excel’s INDEX worksheet function, called as Application.WorksheetFunction.Index(...) or Application.Index(...) to return an…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.