VBA Course: UserForm

To add a UserForm, do exactly as you would if you were adding a new module:

usf userform

The UserForm window and "Toolbox" will appear:

usf2 userform

If you don't see the Properties window, make sure that it is shown and then start by editing the name of the UserForm (so that you can easily find it later on):

properties userform

A UserForm has its own events, just like a workbook or a worksheet. To add events, double click on the UserForm window:

events userform

Now let's create two events as an example of how they work. The first event will define the initial dimensions of the UserForm, and the second will increase each of its dimensions by 50 pixels when the user clicks.

The event UserForm_Initialize will fire when the UserForm is launched:

height userform
Private Sub UserForm_Initialize()
    my_userform.Height = 100
    my_userform.Width = 100
End Sub

To simplify the code, we can use Me instead of the name of the UserForm (since this code is within the UserForm that we're working with):

Private Sub UserForm_Initialize()
    Me.Height = 100
    Me.Width = 100
End Sub

The second event will fire when the user clicks on the UserForm:

Private Sub UserForm_Initialize()
    Me.Height = 100
    Me.Width = 100
End Sub

Private Sub UserForm_Click()
    Me.Height = Me.Height + 50
    Me.Width = Me.Width + 50
End Sub
window userform

Launch a UserForm

To launch a UserForm in a procedure, use Show:

Sub show_userform()
    my_userform.Show
End Sub