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.
Open a Userform using VBA
Use the Show Command to open the Userform called basicUserform:
Close a Userform using VBA
You can close a form using the Unload Command:
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:
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
Note: This code must be placed in the UserForm code module (see picture above).
VBA Coding Made EasyStop 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!