VBA Course: UserForm

To add a UserForm, follow the same steps as for adding a new module:

insert userform png


The UserForm window and the Toolbox window will appear:

usf2 userform

If the Properties window is not visible, display it (F4) and start by modifying the name of the UserForm (for better organization later on):

properties userform

Title of the UserForm

To modify the title of the UserForm, modify its Caption property:

modify userform title

Dimensions of the UserForm

To modify the dimensions of the UserForm, modify its Width and Height properties or resize the UserForm manually:

resize userform
The properties of a UserForm can also be modified using VBA code.

Events of the UserForm

Just like the workbook or its sheets, the UserForm has its own events.

Start by displaying the code of the UserForm:

vba userform code

Then click on UserForm:

events userform

And select the UserForm_Initialize event, which triggers when the UserForm is launched:

Private Sub UserForm_Initialize()

End Sub

For example, let's create two events. The first one to set the initial dimensions of the UserForm, and the second one to increase its dimensions by 50 on each click.

Enter the name of the UserForm followed by a .:

height userform

The Height property is for the height and Width for the width:

Private Sub UserForm_Initialize()

    UserForm_Example.Height = 250
    UserForm_Example.Width = 250

End Sub

To simplify the code, we can replace the name of the UserForm with Me (since this code is placed inside the UserForm we want to act upon):

Private Sub UserForm_Initialize()

    Me.Height = 250
    Me.Width = 250

End Sub

The second event is triggered on a click on the UserForm:

Private Sub UserForm_Initialize()

    Me.Height = 250
    Me.Width = 250

End Sub

Private Sub UserForm_Click()

    Me.Height = Me.Height + 50
    Me.Width = Me.Width + 50

End Sub

Preview of the UserForm (F5):

window userform

Launch a UserForm

To launch a UserForm from a procedure, use Show:

Sub launchUserForm()

    UserForm_Example.Show

End Sub