VBA Open or Close UserForm

Written by

Editorial Team

Reviewed by

Steve Rynearson

Last updated on December 2, 2021

In this tutorial, you will learn how to initialize, open, and close a Userform using VBA.

For this example, we created a simple Userform called basicUserform shown below with a label, a textbox, and three command buttons.

Basic UserForm in VBA

Open a Userform using VBA

Use the Show Command to open the Userform called basicUserform:

basicUserform.Show

Close a Userform using VBA

You can close a form using the Unload Command:

Unload basicUserform

This will close the UserForm from within running code.

 

Instead, you can also use the Me keyword to close a form within the form’s code module:

Unload Me

Note: You can only use Unload Me in procedures contained in the Userform Code Module:

Notice in the example above we added “Unload.Me” to the “Click” event of the Cancel button. So when the user clicks the Cancel button, the form will unload.

You can access the UserForm Code Module by double-clicking on the module in the Code Explorer (on the left). Or by right-clicking in the UserForm visual editor.

Initialize a Userform in VBA

When a form is loaded, the “Initialize” event is triggered. You can use this event to change the UserForm appearance such as populating combo boxes or turning controls on/off in your initialization code.

This code will disable the Cancel button when the UserForm is launched:

Private Sub UserForm_Initialize()

cmdCancel.Enabled = False

End Sub

 

Using the Initialize Event in VBA

Note: This code must be placed in the UserForm code module (see picture above).

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! vba save as


Learn More!
vba-free-addin

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

(No installation required!)

Free Download

Return to VBA Code Examples