TOP

VBA-Lesson 12.1. User forms (UserForm)

To add a UserForm, we need to do the same thing when we add a new module:

After that, a form (UserForm) and a toolbar (Toolbox) will appear:

If you don't see the Properties window (Properties), make sure it is displayed and then start editing the Form name > (so you can easily find it later):

A

Form (UserForm) has its own events, just like a workbook or sheet does. To add an event, double-click on the Form (UserForm).

Now let's create two events to see how this works. The first event will determine the initial size of the Form, and the second event will increase its size by 50px when the user clicks.

The UserForm_Initialize event will fire when the Form is launched:

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 Form name (because this code is in the Form we are working with):

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

The second event will occur when the user clicks on the Form:

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

Starting the Form (UserForm)

To run a Form in a procedure, use a Show method:

Sub show_userform()
      my_userform.Show
End Sub

Articles on the topic:

  • VBA-Lesson 11.2. Worksheet Events
  • VBA-Lesson 12.2. Controls