Excel UserForm events are VBA procedures that run in response to a form’s life cycle or to actions on the form and its controls. The key events include Initialize when a form instance is loaded, Activate when it becomes active, and control events such as Click or Change; choosing the right event helps keep a form responsive and predictable.
What UserForm events do
A UserForm is a custom dialog or window built in the Visual Basic for Applications (VBA) editor. It can collect information, present choices, or guide a user through a task. An event is a signal that something has happened, such as a button being clicked, a text box changing, or the form being closed. VBA runs the event procedure associated with that signal.
Events are not limited to actions by a person. Some controls raise events when VBA changes their values, too. For example, assigning a new value to a text box can trigger its Change event. This matters when an event procedure also edits that control: the edit may cause the same procedure to run again, or may cause other linked procedures to run.
Each event procedure belongs to a particular form or control. A button’s Click event is different from the form’s Click event, and a text box’s Change event is different from a combo box’s Change event. The procedure name usually follows the pattern controlName_EventName, such as cmdSave_Click. Event procedures normally have Private scope and are called by VBA when the relevant event occurs.
The UserForm life cycle
Understanding the form’s life cycle is the best way to choose among its main events. A form can be loaded into memory, shown, hidden, unloaded, and later loaded again. These actions are not interchangeable, and the corresponding events do not all run each time the form appears.
- Initialize: Runs when a particular form instance is loaded, before it is first displayed. It is a suitable place to set initial values, populate lists, or prepare controls. It does not necessarily run every time the same loaded form is shown again.
- Activate: Runs when the form becomes the active window. It can run after initialization and may run again if a modeless form loses and regains focus. Avoid putting one-time setup here unless repeating it is intended.
- QueryClose: Runs when the form is about to close, giving code a chance to check the closing action and cancel it. The event supplies a Cancel argument and a CloseMode argument.
- Terminate: Runs when the form instance is being removed from memory. Hiding a form does not, by itself, unload it or cause it to terminate.
For example, Me.Hide makes the form invisible but retains the instance and its current control values. Unload Me unloads the form; when its object is eventually destroyed, Terminate can run. If code shows the form again after it has been unloaded, VBA loads an instance again and Initialize runs for that new loading. Be deliberate about whether a user should be able to resume a hidden form or start with a clean one.
A form shown with the default Show method is modal: the user must dismiss or hide it before interacting with the rest of Excel. A modeless form, shown with the vbModeless argument, allows interaction with Excel while it remains open. Modeless forms make Activate and focus behavior more noticeable, so code that refreshes data on activation should be safe to run more than once.
Events on buttons, text boxes, and other controls
Most day-to-day form behavior is attached to individual controls. A CommandButton commonly uses Click to run an action. A TextBox or ComboBox commonly uses Change to respond to altered content or selection. Enter and Exit can run when a control receives or loses focus, while KeyDown, KeyPress, and KeyUp respond to keyboard input. Which events are available depends on the specific control.
Use an event that matches the user action and the timing you need. For instance, validate a field when the user leaves it with Exit if immediate feedback is useful, or validate the whole form in the Save button’s Click event before writing any records. A Change event is useful for live feedback, such as enabling a button when required text has been entered, but it can run frequently while someone types.
Control events can interact. Changing a combo box selection might update a label, and changing a text box in response to that selection might raise another Change event. If one procedure updates a control that it also monitors, consider a guard variable, compare old and new values, or move the update into a separate procedure. This avoids accidental loops and makes the intended sequence easier to follow.
How to add an event procedure
In desktop Excel for Windows, open the VBA editor with Alt+F11. In the editor, choose Insert > UserForm to create a form, then add controls from the Toolbox. Select a control and use the Properties window to set a clear name, such as cmdSave or txtCustomer. Naming controls before writing code makes event procedures easier to recognize.
Double-click a control to create its default event procedure, often Click for a button. To choose another event, open the form’s code window and use the object list at the upper left to select the form or control, then choose an event from the list at the upper right. The editor inserts a procedure with the correct signature. Put the event-specific instructions inside that procedure, and use Option Explicit at the top of the module to catch undeclared variable names.
This example assumes a UserForm has a ComboBox named cboRegion, a Label named lblStatus, and a worksheet named Lists with region names in A2:A10. The initialization event fills the list; the Change event displays the current selection.
Option Explicit
Private Sub UserForm_Initialize()
Dim ws As Worksheet
Dim cell As Range
' Load the available regions when this instance is initialized.
Set ws = ThisWorkbook.Worksheets("Lists")
For Each cell In ws.Range("A2:A10").Cells
If Len(cell.Value) > 0 Then Me.cboRegion.AddItem CStr(cell.Value)
Next cell
End Sub
Private Sub cboRegion_Change()
' Reflect the current selection in the status label.
Me.lblStatus.Caption = "Selected: " & Me.cboRegion.Value
End Sub
Before running any VBA macro, save a copy of the workbook. Macro changes cannot be undone with Ctrl+Z. Also confirm that the named worksheet and controls exist; a misspelled control name or missing sheet can stop the procedure with a run-time error.
Choosing the right event
A useful rule is to put setup in Initialize, response to a user action in the relevant control event, and close-time checks in QueryClose. Activate is for work that genuinely needs to happen whenever the form becomes active. Keeping those roles separate prevents setup from being repeated unexpectedly and makes the form easier to maintain.
- Populate a list once per loaded instance: use Initialize.
- Run a search after the user presses a Search button: use that button’s Click event.
- Show a live character count while the user types: use the text box’s Change event.
- Prevent closing while required information is missing: use QueryClose, or validate before hiding or unloading the form.
- Refresh information whenever a modeless form becomes active: consider Activate, while ensuring the refresh can safely repeat.
QueryClose can distinguish how the form is being closed. Its CloseMode argument identifies the closing route, including the form’s control-menu close button and an Unload statement. The Cancel argument lets code prevent closure. A confirmation prompt can therefore be limited to a user closing the window, rather than appearing during every programmatic unload. Do not assume that hiding a form runs QueryClose: hiding is not closing.
Common event problems and fixes
Initialization appears to run only once. That is expected if the same instance remains loaded. Hide preserves it; showing it again does not necessarily create a fresh instance. Unload the form when a fresh initialization is required, or explicitly reset its controls when the user starts a new entry.
A Change event fires more than expected. It may run for programmatic value changes as well as user edits. Keep event code short, avoid assigning to the same control without a reason, and use a Boolean guard when several linked updates must be coordinated. For example, a private module-level flag can be set during a batch update and checked before responding to Change.
Code runs twice or the form behaves differently after reopening. Check whether the action is being handled in both a control event and another procedure it calls. Also check whether a form was hidden rather than unloaded, and whether initialization code is being placed in Activate. A clear division between setup, user actions, and closing logic usually reveals the cause.
Closing cannot be stopped, or a prompt appears at the wrong time. In QueryClose, set Cancel to True when the close should be blocked, and test CloseMode if the rule applies only to a specific closing method. If code uses Hide, no close event is expected from that action. Test each route the form supports, including its close button and any Cancel or Exit button.
Good design for reliable forms
Keep event procedures focused: they should handle the event and delegate substantial work to clearly named helper procedures. For example, a Save button can check required fields, call a routine that writes a record, and then hide or unload the form. This separation makes it easier to reuse validation and to identify whether a problem comes from the control event or the underlying task.
Validate before changing a worksheet. Check that required fields are present and that values have the expected type or format, then write the complete record. If several events can update the same worksheet, centralize that update logic instead of duplicating it across handlers. Avoid relying on the active sheet or active cell when a form can refer directly to a known workbook, worksheet, and range.
For forms that can be shown repeatedly, decide what should persist. A search dialog may reasonably keep its last criteria when hidden; an order-entry form may need a reset after saving. Make that behavior explicit rather than assuming that closing, hiding, and reopening all clear the controls.
Excel platform and VBA considerations
VBA UserForms are for desktop Excel, not Excel for the web; the web app does not run VBA macros. Excel for Mac supports VBA, but interface details, keyboard shortcuts, and some controls or behaviors can differ from Windows. If a workbook must work on both desktop platforms, test its forms and controls on each platform and avoid assuming that a Windows-only component is available on a Mac.
On Windows, Alt+F11 opens the VBA editor in Excel. On many Mac keyboards, Option+F11 is the corresponding shortcut, though the Fn key may also be needed depending on keyboard settings. The VBE menus and available controls can differ on Mac. A workbook containing VBA must be saved in a macro-enabled format such as .xlsm if the VBA project is to be retained. Users may also need to enable macros according to their organization’s security policy; they should not enable macros in files from untrusted sources.
Frequently Asked Questions
What is the difference between Initialize and Activate? Initialize runs when a form instance is loaded. Activate runs when the form becomes active and can run again when it regains focus. Put one-time setup in Initialize and repeatable focus-related work in Activate.
Does hiding a UserForm trigger Terminate? No. Hide makes the form invisible while keeping the instance loaded, so its values remain available. Terminate relates to destruction of the instance, not simply making it invisible.
How do I run code when a UserForm button is clicked? Create a Click event procedure for that button, typically by double-clicking it in the form designer. Put the action in the generated procedure or call a separate routine from it.
Why does a TextBox Change event run when VBA changes its value? Change responds to a change in the control’s value, not only to typing by a person. If code assigns a value, the event may run; guard against unwanted repeat work when updating controls programmatically.
Can I stop a UserForm from closing? Yes. Use the form’s QueryClose event and set its Cancel argument to True when the closing action should be blocked. Check CloseMode if the rule should apply only to a particular way of closing the form.