Excel vba initialise userform

Пример создания пользовательской формы в редакторе VBA Excel для начинающих программировать с нуля. Добавление на форму текстового поля и кнопки.

Начинаем программировать с нуля
Часть 4. Первая форма
[Часть 1] [Часть 2] [Часть 3] [Часть 4]

Создание пользовательской формы

Создайте или откройте файл Excel с расширением .xlsm (Книга Excel с поддержкой макросов) или с расширением .xls в старых версиях приложения.

Перейдите в редактор VBA, нажав сочетание клавиш «Левая_клавиша_Alt+F11».

В открывшемся окне редактора VBA выберите вкладку «Insert» главного меню и нажмите кнопку «UserForm». То же подменю откроется при нажатии на вторую кнопку (после значка Excel) на панели инструментов.

На экране редактора VBA появится новая пользовательская форма с именем «UserForm1»:

Добавление элементов управления

Обычно вместе с пользовательской формой открывается панель инструментов «Toolbox», как на изображении выше, с набором элементов управления формы. Если панель инструментов «Toolbox» не отобразилась, ее можно вызвать, нажав кнопку «Toolbox» во вкладке «View»:

При наведении курсора на элементы управления появляются подсказки.

Найдите на панели инструментов «Toolbox» элемент управления с подсказкой «TextBox», кликните по нему и, затем, кликните в любом месте рабочего поля формы. Элемент управления «TextBox» (текстовое поле) будет добавлен на форму.

Найдите на панели инструментов «Toolbox» элемент управления с подсказкой «CommandButton», кликните по нему и, затем, кликните в любом месте рабочего поля формы. Элемент управления «CommandButton» (кнопка) будет добавлен на форму.

Кликнув по элементу управления на форме, вы можете изменять его размер, перетягивая границы за белые квадратики, и перетаскивать по форме, ухватив за одну из границ. Кликнув по заголовку формы или по ее рабочему полю, вы можете также изменять ее размер, перетягивая границы за белые квадратики.

Нажатием клавиши «F4» вызывается окно свойств, с помощью которого можно вручную задавать значения свойств пользовательской формы и элементов управления. В окне свойств отображаются свойства выбранного элемента управления или формы, если выбрана она. Также окно свойств можно вызвать, нажав кнопку «Properties Window» во вкладке «View».

Отображение формы на экране

Чтобы запустить пользовательскую форму для просмотра из редактора VBA, необходимо выбрать ее, кликнув по заголовку или свободному от элементов управления полю, и совершить одно из трех действий:

  • нажать клавишу «F5»;
  • нажать на треугольник на панели инструментов (на изображении выше треугольник находится под вкладкой «Debug»);
  • нажать кнопку «Run Sub/UserForm» во вкладке «Run».

Для запуска пользовательской формы с рабочего листа Excel, можно использовать кнопки, описанные в этой статье. Например, чтобы отобразить форму с помощью «кнопки – элемента ActiveX», используйте в модуле рабочего листа следующий код:

Private Sub CommandButton1_Click()

    UserForm1.Show

End Sub

Для «кнопки – элемента управления формы» можно использовать следующий код, размещенный в стандартном программном модуле:

Sub ShowUserForm()

    UserForm1.Show

End Sub

В результате вышеперечисленных действий мы получаем на рабочем листе Excel пользовательскую форму с мигающим курсором в текстовом поле:

Добавление программного кода

Программный код для пользовательской формы и элементов управления формы записывается в модуль формы. Перейти в модуль формы можно через контекстное меню, кликнув правой кнопкой мыши на поле формы или на ссылке «UserForm1» в проводнике слева и нажав кнопку «View Code».

Переходить между открытыми окнами в редакторе VBA можно через вкладку «Window» главного меню.

Изменить название пользовательской формы и элементов управления, их размеры и другие свойства можно через окно свойств (Properties Window), которое можно отобразить клавишей «F4». Мы же это сделаем с помощью кода VBA Excel, записанного в модуль формы.

Откройте модуль формы, кликнув правой кнопкой мыши по форме и нажав кнопку «View Code» контекстного меню. Скопируйте следующий код VBA, который будет задавать значения свойств формы и элементов управления перед ее отображением на экране:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

Private Sub UserForm_Initialize()

    ‘Me — это обращение к форме в ее модуле

    With Me

        ‘Присваиваем форме заголовок

        .Caption = «Новая форма»

        ‘Задаем ширину формы

        .Width = 300

        ‘Задаем высоту формы

        .Height = 150

    End With

    With TextBox1

        ‘Задаем ширину текстового поля

        .Width = 200

        ‘Задаем высоту текстового поля

        .Height = 20

        ‘Задаем расстояние от внутреннего края

        ‘формы сверху до текстового поля

        .Top = 30

        ‘Задаем расстояние от внутреннего края

        ‘формы слева до текстового поля, чтобы

        ‘текстовое поле оказалось по центру

        .Left = Me.Width / 2 .Width / 2 6

        ‘Задаем размер шрифта

        .Font.Size = 12

        ‘Присваиваем текст по умолчанию

        .Text = «Напишите что-нибудь своё!»

    End With

    With CommandButton1

        ‘Задаем ширину кнопки

        .Width = 70

        ‘Задаем высоту кнопки

        .Height = 25

        ‘Задаем расстояние от внутреннего края

        ‘формы сверху до кнопки

        .Top = 70

        ‘Задаем расстояние от внутреннего края

        ‘формы слева до кнопки, чтобы

        ‘кнопка оказалось по центру

        .Left = Me.Width / 2 .Width / 2 6

        ‘Задаем размер шрифта

        .Font.Size = 12

        ‘Присваиваем кнопке название

        .Caption = «OK»

    End With

End Sub

Вставьте скопированный код в модуль формы:

Познакомьтесь еще с одним способом отображения на экране пользовательской формы в процессе тестирования: установите курсор внутри процедуры UserForm_Initialize() и нажмите клавишу «F5» или треугольник на панели инструментов. Все предыдущие способы (с выбором формы в редакторе и кнопками на рабочем листе) тоже работают.

В результате мы получаем следующую форму:

Теперь перейдите в редактор VBA, откройте проект формы «UserForm1» и дважды кликните по кнопке «CommandButton1». В результате откроется модуль формы и будет создан шаблон процедуры CommandButton1_Click(), которая будет запускаться при нажатии кнопки:

Private Sub CommandButton1_Click()

End Sub

Вставьте внутрь шаблона процедуры CommandButton1_Click() следующую строку кода, которая будет копировать текст из текстового поля в ячейку «A1» активного рабочего листа:

Range(«A1») = TextBox1.Text

Отобразите пользовательскую форму на экране и проверьте работоспособность кнопки «OK».


Return to VBA Code Examples

This article will demonstrate the role of the userform_initialize event in VBA.

vba initialize event

UserForm_Initialize Event

The UserForm_Initialize event runs when the UserForm is first opened.

Often it will contain code to populate controls such as ComboBoxes, or adjust which controls are visible.

Customize UserFormControls

This example will populate a ComboBox in a UserForm:

Private Sub UserForm_Initialize()
  Me.Caption = "Enter Order Details"
  Me.BackColor = vbYellow  
  Me.cmdCancel.Enabled = False
'add items to the combo box
  Me.cboRep.AddItem "Bob Smith"
  Me.cboRep.AddItem "Jane Doe"
  Me.cboRep.AddItem "Jim Jones"
  Me.cboRep.AddItem "Brad Hilbert"
  Me.cboRep.AddItem "Sandy Sinatra"
End Sub

This code would result in the following items being added to the drop down list “Rep”.

vba initialize dropdown

UserForm Properties

You can also use the Initialize event to adjust properties of the UserForm itself.

This UserForm_Initialize event will do the following:

  • Set the UserForm Caption
  • Set the UserForm background color
  • Disable the Cancel button.
Private Sub UserForm_Initialize()
  Me.Caption = "Enter Order Details"
  Me.BackColor = vbYellow
  Me.cmdCancel.Enabled = False
End Sub

vba initialize macro

This post provides an in-depth guide to the VBA Userform starting from scratch.

The table of contents below shows the areas of the VBA UserForm that are covered and the section after this provides a quick guide so you can refer back to the UserForm code easily.

“The system should treat all user input as sacred.” – Jef Raskin

A Quick Guide to the VBA UserForm

The following table provides a quick guide to the most common features of the UserForm

Function Examples
Declare and create Dim form As New userformCars
Declare and create Dim form As userformCars
Set form = New userformCars
Show as modal form.Show
OR
form.Show vbModal
Show as non modal form.Show vbModeless
Unload Private Sub buttonCancel_Click()
  Unload Me
End Sub
Hide Private Sub buttonCancel_Click()
  Hide
End Sub
Getset the title form.Caption = «Car Details»

The Webinar

If you are a member of the website, click on the image below to view the webinar for this post.

(Note: Website members have access to the full webinar archive.)

vba userform1 video

Introduction

The VBA UserForm is a very useful tool. It provides a practical way for your application to get information from the user.

If you are new to UserForms you may be overwhelmed by the amount of information about them. As with most topics in VBA, 90% of the time you will only need 10% of the functionality.

In these two blog posts(part 2 is here) I will show you how to quickly and easily add a UserForm to your application.

This first post covers creating the VBA Userform and using it as modal or modeless. I will also show you how to easily pass the users selection back to the calling procedure.

In the second part of this post I will cover the main controls such as the ListBox, the ComboBox(also called the Dropdown menu), the TextBox and the CheckBox. This post will contain a ton of examples showing how to use each of these controls.

Related Articles

VBA Message Box
VBA UserForm Controls

Download the Code

What is the VBA Userform?

The VBA UserForm is a dialog which allows your application to get input from the user. UserForms are used throughout all Windows applications. Excel itself has a large number of UserForms such as the Format Cells UserForm shown in the screenshot below.

VBA Userform

Excel’s “Format cells” UserForm

UserForms contain different types of controls such as Buttons, ListBoxes, ComboBoxes(Dropdown lists), CheckBoxes and TextBoxes.

In the Format Cells screenshot above you can see examples of these controls:

  • Font, Font style and Size contain a textbox with a ListBox below it
  • Underline and Color use a Combobox
  • Effects uses three CheckBoxes
  • Ok and Cancel are command Buttons

There are other controls but these are the ones you will use most of the time.

The Built-in VBA Userforms

It is important to note that VBA has some useful built-in UserForms. These can be very useful and may save you having to create a custom one. Let’s start by having a look at the MsgBox.

VBA MsgBox

The VBA message box allows you to display a dialog to the user. You can choose from a collection of buttons such as Yes, No, Ok and Cancel.

VBA MsgBox

You can easily find out which of these buttons the user clicked on and use the results in your code.

The following code shows two simple examples of using a message box

' https://excelmacromastery.com/
Sub BasicMessage()

    ' Basic message
    MsgBox "There is no data on this worksheet "
    ' Basic message with "Error" as title
    MsgBox "There is no data on this worksheet ", , "Error"

End Sub

In the next example, we ask the user to click Yes or No and print a message displaying which button was clicked

' https://excelmacromastery.com/
Sub MessagesYesNoWithResponse()

    ' Display Yes/No buttons and get response
    If MsgBox("Do you wish to continue? ", vbYesNo) = vbYes Then
        Debug.Print "The user clicked Yes"
    Else
        Debug.Print "The user clicked No"
    End If

End Sub

In the final example we ask the user to click Yes, No or Cancel

' https://excelmacromastery.com/
Sub MessagesYesNoCancel()

    ' Display Yes/No buttons and get response
    Dim vbResult As VbMsgBoxResult

    vbResult = MsgBox("Do you wish to continue? ", vbYesNoCancel)

    If vbResult = vbYes Then
        Debug.Print "The user clicked Yes"
    ElseIf vbResult = vbNo Then
        Debug.Print "The user clicked No"
    Else
        Debug.Print "The user clicked Cancel"
    End If

End Sub

You can see all the MsgBox options here.

InputBox

If you want to get a single piece of text or value from the user you can use the InputBox. The following code asks the user for a name and writes it to the Immediate Window(Ctrl + G):

' Description: Gets a value from the InputBox
' The result is written to the Immediate Window(Ctrl + G)
' https://excelmacromastery.com/vba-userform/
Sub GetValue()

    Dim sValue As String
    sValue = Application.InputBox("Please enter your name", "Name Entry")
    
    ' Print to the Immediate Window
    Debug.Print sValue

End Sub

You can add validation to the InputBox function using the Type parameter:

' https://excelmacromastery.com/
Public Sub InputBoxTypes()

    With Application
        Debug.Print .InputBox("Formula", Type:=0)
        Debug.Print .InputBox("Number", Type:=1)
        Debug.Print .InputBox("Text", Type:=2)
        Debug.Print .InputBox("Boolean", Type:=4)
        Debug.Print .InputBox("Range", Type:=8)
        Debug.Print .InputBox("Error Value", Type:=16)
        Debug.Print .InputBox("Array", Type:=64)
    End With
    
End Sub

You can download the workbook with all the code examples from the top of this post.

GetOpenFilename

We can use the Windows file dialog to allow the user to select a file or multiple files.

The first example allows the user to select a file

' Print the name of the selected file
sfile = Application.GetOpenFilename("Excel Files (*.xlsx),*.xlsx")
Debug.Print sfile

The following example allows the user to select multiple files

' https://excelmacromastery.com/
Sub GetMultipleFiles()
    
    Dim arr As Variant
    arr = Application.GetOpenFilename("Text Files(*.txt),*.txt" _ 
        , MultiSelect:=True)

    ' Print all the selected filenames to the Immediate window
    Dim filename As Variant
    For Each filename In arr
        Debug.Print filename
    Next
    
End Sub

Note: If you need more flexibility then you can use the File Dialog. This allows you to use the “Save as” file dialog, select folders and so on.

How to Create a VBA UserForm

If the built-in UserForms do not cover your needs then you will need to create your own custom Userform. To use a UserForm in our code we must first create one. We then add the necessary controls to this Userform.

We create a UserForm with the following steps

  1. Open the Visual Basic Editor(Alt + F11 from Excel)
  2. Go to the Project Window which is normally on the left(select View->Project Explorer if it’s not visible)
  3. Right-click on the workbook you wish to use
  4. Select Insert and then UserForm(see screenshot below)

VBA Userform Create

Creating a Userform

A newly created UserForm will appear. Anytime you want to access this Userform you can double click on the UserForm name in the Project window.

The Toolbox dialog should also be visible. If it’s not visible select View->Toolbox from the menu. We use the toolbox too add controls to our UserForm.

VBA Toolbox

The UserForm Toolbox

Designing the VBA UserForm

To view the design of the UserForm, double click on it in the Project window. There are three important windows we use when creating our UserForms.

  1. The UserForm
  2. The properties window – this is where we can change the setting of the Userform and its controls
  3. The toolbox – we use this to add new controls to our UserForm

VBA UserForm

UserForm Windows

A Very Simple VBA UserForm Example

Let’s have a look at a very simple UserForm example.

You can download this and all the code examples from the top of this post.

  1. Create a new UserForm
  2. Rename it to userformTest in the (Name) property in the properties window
  3. Create a new module(Right-click on properties window and select Insert->Module)
  4. Copy the DislayUserForm sub below to the module
  5. Run the sub using Run->Run UserForm Sub from the menu
  6. The UserForm will be displayed – you have created your first UserForm application!
  7. Click on the X in the top right of the UserForm to close
' https://excelmacromastery.com/
Sub DisplayUserForm()
    
    Dim form As New UserFormTest  
    form.Show
    
End Sub

Setting the Properties of the UserForm

We can change the attributes of the UserForm using the properties window. Select View->Properties Window if the window is not visible.

When we click on the UserForm or a control on a UserForm then the Properties window displays the attributes of that item.

VBA Properties Window

VBA Properties Window

Generally speaking, you only use a few of these properties. The important ones for the UserForm are Name and Caption.

To change the name of the UserForm do the following

  1. Click on the UserForm in the Project window or click on the UserForm itself
  2. Click in the name field of the properties window
  3. Type in the new name

The Controls of the VBA UserForm

We add controls to the UserForms to allow the user to make selections, enter text or click a button. To add a control use the steps below

  1. Go to the toolbox dialog – if not visible select View->Toolbox
  2. Click on the control you want to add – the button for this control will appear flat
  3. Put the cursor over the UserForm
  4. Hold down the left mouse button and drag until the size you want

The following table shows a list of the common controls

Control Description
CheckBox Turn item on/off
ComboBox Allows selection from a list of items
CommandButton Click to perform action
Label Displays text
ListBox Allows selection from a list of items
Textbox Allows text entry

Adding Code to the VBA UserForm

To view the code of the UserForm

  1. Right-click on the UserForm in the properties windows(or the UserForm itself) and select “View Code”
  2. You will see a sub called UserForm_Click. You can delete this when you create your first sub

Note: If you double click on a control it will bring you to the click event of that control. This can be a quicker way to get to the UserForm code.

Adding Events to the VBA UserForm

When we use a UserForm we are dealing with events. What this means is that we want to perform actions when events occur. An event occurs when the users clicks a button, changes text, selects an item in a ComboBox, etc. We add a Sub for a particular event and place our code in it. When the event occurs our code will run.

One common event is the Initialize event which occurs when the UserForm is created at run time. We normally use this event to fill our controls with any necessary data. We will look at this event in the section below.

VBA Event combobox

To add an event we use the ComboBoxes over the code window(see screenshot above). The left one is used to select the control and the right one is used to select the event. When we select the event it will automatically add this sub to our UserForm module.

Note: Clicking on any control on the UserForm will create the click event for that control.

The Initialize Event of the VBA UserForm

The first thing we want to do with a UserForm is to fill the controls with values. For example, if we have a list of countries for the user to select from we could use this.

To do this we use the Initialize event. This is a sub that runs when the UserForm is created(see next section for more info).

To create the Initialize event we do the following

  1. Right-click on the UserForm and select View Code from the menu.
  2. In the Dropdown list on the left above the main Window, select UserForm.
  3. This will create the UserForm_Click event. You can ignore this.
  4. In the Dropdown list on the right above the main Window, select Initialize.
  5. Optional: Delete the UserForm_Click sub created in step 2.

VBA Userform Initialize

Adding the Initialize Event

We can also create the Initialize event by copying or typing the following code

Private Sub UserForm_Initialize()

End Sub

Once we have the Initialize event created we can use it to add the starting values to our controls. We will see more about this in the second part of this post.

Initialize versus Activate

The UserForm also has an Activate event. It is important to understand the difference between this and the Initialize event.

The Initialize event occurs when the actual object is created. This means as soon as you use on of the properties or functions of the UserForm. The code example below demonstrates this

Dim frm As New UserForm1

' Initialize will run as UserForm is created 
' the first time we use it
frm.BackColor = rgbBlue

frm.Show

We normally reference the UserForm first by calling Show which makes it seem that displaying the UserForm is triggering the Initialize event. This is why there is often confusion over this event.

In the example below calling Show is the first time we use the UserForm. Therefore it is created at this time and the Initialize event is triggered.

Dim frm As New UserForm1

' Initialize will run here as the Show is the 
' first time we use the UserForm
frm.Show

The Activate event occurs when the UserForm is displayed. This can happen using Show. It also occurs any time the UserForm is displayed. For example, if we switch to a different window and then switch back to the UserForm then the Activate event will be triggered.

We create the Activate event the same way we create the Initialize event or we can just copy or type the following code

Private Sub UserForm_Activate()

End Sub
  1. Initialize occurs when the Userform is created. Activate occurs when the UserForm is displayed.
  2. For each UserForm you use – Initialize occurs only once, Activate occurs one or more times.

Calling the VBA UserForm

We can use the VBA UserForm in two ways

  1. Modal
  2. Modeless

Let’s look at each of these in turn.

Modal Userform

Modal means the user cannot interact with the parent application while this is visible. The excel Format cells dialog we looked at earlier is a modal UserForm. So are the Excel Colors and Name Manager dialogs.

We use modal when we don’t want the user to interact with any other part of the application until they are finished with the UserForm.

Modeless Userform

Modeless means the user can interact with other parts of the application while they are visible. An example of modeless forms in Excel is the Find dialog(Ctrl + F).

You may notice that any Excel dialog that allows the user to select a range has a limited type of Modeless – the user can select a range of cells but cannot do much else.

Modal versus Modeless

The actual code to make a UserForm modal or modeless is very simple. We determine which type we are using when we show the UserForm as the code below demonstrates

Dim frm As New UserFormFruit

' Show as modal - code waits here until UserForm is closed
frm.Show vbModal

' Show as modeless - code does not wait
frm.Show vbModeless

' default is modal
frm.Show 

As the comments above indicate, the code behaves differently for Modal and Modeless. For the former, it waits for the UserForm to close and for the latter, it continues on.

Even though we can display any UserForm as modal or modeless we normally use it in one way only. This is because how we use them is different

Typical use of a Modal form

With a Modal UserForm we normally have an Ok and a Cancel button.

VBA UserForm

The Ok button normally closes the UserForm and performs the main action. This could be saving the user inputs or passing them back to the procedure.

The Cancel button normally closes the UserForm and cancels any action that may have taken place. Any changes the user made on the UserForm are ignored.

Typical use of a Modeless form

With a Modeless UserForm we normally have a close button and an action button e.g. the Find button on the Excel Find Dialog.

When the action button is clicked an action takes place but the dialog remains open.

The Close button is used to close the dialog. It normally doesn’t do anything else.

A VBA UserForm Modal Example

We are going to create a Modal UserForm example. It is very simple so you can see clearly how to use a UserForm.

You can download this and all the code examples from the top of this post.

The following UserForm allows the user to enter the name of a fruit:

VBA Modal dialog example

We use the following code to show this UserForm and to retrieve the contents of the fruit textbox:

' PROCEDURE CODE
' https://excelmacromastery.com/
Sub UseModal()

    ' Create and show form
    Dim frm As New UserFormFruit

    ' Display Userform - The code in this procedure 
    ' will wait here until the form is closed
    frm.Show
    
    ' Display the returned value
    MsgBox "The user has selected " & frm.Fruit
        
    ' Close the form
    Unload frm
    Set frm = Nothing

End Sub

' USERFORM CODE
' Returns the textbox value to the calling procedure
Public Property Get Fruit() As String
    Fruit = textboxFruit.Value
End Property

' Hide the UserForm when the user click Ok
Private Sub buttonOk_Click()
    Hide
End Sub

What you will notice is that we hide the UserForm when the user clicks Ok. We don’t set it to Nothing or unload it until after we are finished retrieving the user input. If we Unload the UserForm when the user clicks Ok then it no longers exists so we cannot access the values we want.

Using UserForm_QueryClose to Cancel the UserForm

We always want to give the user the option to cancel the UserForm. Once it is canceled we want to ignore any selections the user made.

Each form comes with an X in the top right-hand corner which allows the user to cancel it:

VBA Userform X

The X button on the UserForm

This button cancels the UserForm automatically – no code is necessary. When the user clicks X the UserForm is unloaded from memory. That is, it no longer exists so we will get an error if we try to access it. The code below will give an error if the user clicks on the X

' https://excelmacromastery.com/
Sub DisplayFruit()
    
    Dim frm As New UserFormFruit
    frm.Show
        
    ' ERROR HERE - If user clicks the X button
    Debug.Print frm.Fruit
    
End Sub

VBA Automation Error

To avoid this error we want to prevent the UserForm from being Unloaded when the X button is clicked. To do this we use the QueryClose event.

We create a variable first at the top of the UserForm code module. We also add a property so that we can read the variable when we need to retrieve the value:

Private m_Cancelled As Boolean

Public Property Get Cancelled() As Variant
    Cancelled = m_Cancelled
End Property

Then we add the UserForm_QueryClose event to the UserForm module:

' https://excelmacromastery.com/
Private Sub UserForm_QueryClose(Cancel As Integer _
                                       , CloseMode As Integer)
    
    ' Prevent the form being unloaded
    If CloseMode = vbFormControlMenu Then Cancel = True
    
    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True
    
End Sub

In the first line, we prevent the UserForm from being unloaded. With the next lines, we hide the UserForm and set the m_Cancelled variable to true. We will use this variable later to check if the UserForm was canceled:

We can then update our calling procedure to check if the UserForm was canceled

' PROCEDURE CODE
' https://excelmacromastery.com/
Sub DisplayFruit()
    
    Dim frm As New UserFormFruit
    frm.Show
        
    If frm.Cancelled = False Then
        MsgBox "You entered: " & frm.Fruit
    Else
        MsgBox "The UserForm was cancelled."
    End If
    
End Sub

If we want to add a Cancel button it is simple to do. All we need to do is Hide the form and set the variable m_Cancelled to true. This is the same as we did in the QueryClose Event above:

' https://excelmacromastery.com/vba-userform/
Private Sub buttonCancel_Click()
    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True
End Sub

VBA Modal dialog example with Cancel

Using the Escape key to cancel

If you want to allow the user to cancel using the Esc it is simple(but not obvious) to do. You set the Cancel property of your ‘Cancel’ button to True. When Esc is pressed the click event of your Cancel button will be used.

VBA Cancel property

Putting All the Modal Code Together

The final code for a Modal form looks like this:

' USERFORM CODE
' https://excelmacromastery.com/
Private m_Cancelled As Boolean

' Returns the cancelled value to the calling procedure
Public Property Get Cancelled() As Boolean
    Cancelled = m_Cancelled
End Property

' Returns the textbox value to the calling procedure
Public Property Get Fruit() As String
    Fruit = textboxFruit.Value
End Property
 
Private Sub buttonCancel_Click()
    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True
End Sub

' Hide the UserForm when the user click Ok
Private Sub buttonOk_Click()
    Hide
End Sub

' Handle user clicking on the X button
Private Sub UserForm_QueryClose(Cancel As Integer _
                                  , CloseMode As Integer)
    
    ' Prevent the form being unloaded
    If CloseMode = vbFormControlMenu Then Cancel = True
    
    ' Hide the Userform and set cancelled to true
    Hide
    m_Cancelled = True
    
End Sub

' PROCEDURE CODE
' https://excelmacromastery.com/
Sub DisplayFruit()
    
    ' Create the UserForm
    Dim frm As New UserFormFruit
    
    ' Display the UserForm
    frm.Show
    
    ' Check if the user cancelled the UserForm
    If frm.Cancelled = True Then
        MsgBox "The UserForm was cancelled."
    Else
        MsgBox "You entered: " & frm.Fruit
    End If
    
    ' Clean up
    Unload frm
    Set frm = Nothing
    
End Sub

&nbps;
You can use this code as a framework for any Modal UserForm that you create.

VBA Minimize UserForm Error

We are now going to use a simple example to show how to use a Modeless VBA UserForm. In this example, we will add a customer name to a worksheet each time the user clicks on the Add Customer button.

You can download this and all the code examples from the top of this post.

VBA Modeless Userform example

The code below displays the UserForm in Modeless mode. The problem with this code is that if you minimize Excel the UserForm may not be visible when you restore it:

' PROCEDURE CODE
' https://excelmacromastery.com/
Sub UseModeless()

    Dim frm As New UserFormCustomer
    ' Unlike the modal state the code will NOT
    ' wait here until the form is closed
    frm.Show vbModeless
    
End Sub

The code below solves the problem above. When you display a Userform using this code it will remain visible when you minimize and restore Excel:

' https://excelmacromastery.com/
Sub UseModelessCorrect()

    Dim frm As Object
    Set frm = VBA.UserForms.Add("UserFormCustomer")
    
    frm.Show vbModeless
    
End Sub

An important thing to keep in mind here is that after the frm.Show line, the code will continue on. This is different to Modal where the code waits at this line for the UserForm to be closed or hidden.

When the Add button is clicked the action occurs immediately. We add the customer name to a new row in our worksheet. We can add as many names as we like. The UserForm will remain visible until we click on the Close button.

The following is the UserForm code for the customer example:

' USERFORM CODE
' https://excelmacromastery.com/
Private Sub buttonAdd_Click()
    InsertRow
End Sub

Private Sub buttonClose_Click()
    Unload Me
End Sub

Private Sub InsertRow()
    
    With Sheet1
    
        ' Get the current row
        Dim curRow As Long
        If .Range("A1") = "" Then
            curRow = 1
        Else
            curRow = .Range("A" & .Rows.Count).End(xlUp).Row + 1
        End If
        
        ' Add item
        .Cells(curRow, 1) = textboxFirstname.Value
        .Cells(curRow, 2) = textboxSurname.Value
        
    End With
    
End Sub

Part 2 of this post

You can find the second part of this post here.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

В настоящей заметке рассматриваются методы создания пользовательских форм и работы с ними.[1] Пользовательские диалоговые окна создаются на основе технологии пользовательских форм, к которым можно получить доступ из редактора Visual Basic (VBE; подробнее см. Настройка среды Visual Basic Editor).

Рис. 1. Окно новой пустой формы UserForm

Скачать заметку в формате Word или pdf, примеры в формате архива

Стандартная последовательность шагов при этом следующая:

  1. Вставьте новую форму UserForm в проект VBAProject рабочей книги.
  2. Добавьте элементы управления в форму UserForm.
  3. Настройте свойства добавленных элементов управления.
  4. Создайте процедуры «обработчики событий» для элементов управления. Эти процедуры добавляются в модуль кода UserForm и выполняются при возникновении различных событий (например, при щелчке на кнопке).
  5. Разработайте процедуру, которая отображает форму UserForm. Эта процедура находится в модуле VBA (а не в модуле кода для формы UserForm).
  6. Определите простой способ вызова на выполнение процедуры, созданной в п. 5. Можно поместить кнопку на рабочий лист, команду ленты и т.д.

Рассмотрим эти шаги подробнее.

Вставка новой формы UserForm

Чтобы добавить в проект форму UserForm, запустите VBE (например, нажав в Excel клавиши <Alt+F11>), выберите рабочую книгу в окне Project и выполните команду Inserts –> UserForm). Формы UserForm получают такие имена, как UserForm1, UserForm2 и т.д. Можно переименовать форму, изменив свойство Name в окне Properties (см. рис. 1). Если это окно не отображается, нажмите в VBE клавишу <F4>. В рабочей книге может быть произвольное количество форм UserForm, а каждая форма включает единственное пользовательское диалоговое окно.

Добавление элементов управления в пользовательское диалоговое окно

Чтобы добавить элементы управления в форму UserForm, воспользуйтесь панелью Toolbox. Обратите внимание, что в VBE отсутствуют команды меню, предназначенные для добавления элементов управления. Если панель Toolbox не отображена на экране, пройдите по меню View –> Toolbox (рис. 2).

Рис. 2. Окно Toolbox для добавления элементов управления в пользовательскую форму

Щелкните на той кнопке в панели Toolbox, которая соответствует добавляемому элементу управления. После этого щелкните внутри диалогового окна для создания элемента управления (используется размер элемента по умолчанию). Также можно щелкнуть на элементе управления и, перетащив его границы в диалоговом окне, задать необходимый размер в пользовательском диалоговом окне. Добавленному элементу управления назначается имя, которое состоит из названия типа элемента управления и числового кода. Рекомендуется их переименовать, чтобы в коде VBA было понятно, с чем вы имеете дело. Согласитесь, что РrоductListBox звучит лучше, чем ListBox1.

Элементы управления в окне Toolbox

Форма UserForm, которая показана на рис. 3, размещена в файле all userform controls.xlsm.

Рис. 3. Эта форма UserForm содержит 15 элементов управления

Элемент управления CheckBox (6) предоставляет пользователю возможность выбрать один из двух вариантов: включить или выключить. Если галочка установлена, то CheckBox имеет значение True, в противном случае – False.

ComboBox (4) подобен объекту ListBox (5). Отличие заключается в том, что ComboBox представляет раскрывающийся список, в котором в определенный момент времени отображается только одно значение. Кроме того, пользователю в поле списка разрешено вводить значение, которое необязательно представляет одну из опций объекта ComboBox.

Каждое создаваемое диалоговое окно будет иметь как минимум один элемент управления CommandButton (10). Обычно используются кнопки ОК и Отмена.

Элемент управления Frame (9) применяется в качестве оболочки для других элементов управления. Он добавляется в диалоговое окно либо в целях эстетики, либо из соображений логического группирования однотипных элементов управления. Элемент управления Frame требуется в случае, если в диалоговом окне содержится более одного набора элементов управления OptionButton.

Элемент управления Image (15) используется для представления графического изображения, которое сохранено в отдельном файле или вставляется из буфера обмена. Графическое изображение сохраняется вместе с рабочей книгой. Таким образом, вместе с рабочей книгой передавать другому пользователю копию графического файла необязательно. Некоторые графические файлы занимают много места, поэтому их включение в рабочую книгу приведет к радикальному увеличению ее размера.

Элемент управления Label (2) отображает текст в диалоговом окне.

Элемент управления ListBox (5) предоставляет список опций, из которого пользователь может выбрать один вариант (или несколько). Вы вправе указать диапазон на листе, который содержит элементы списка. Этот диапазон может состоять из нескольких столбцов. Кроме того, элемент управления ListBox может заполняться с помощью кода VBA.

Элемент управления MultiPage (12) позволяет создавать диалоговые окна с несколькими вкладками, которые подобны появляющимся после выбора команды Формат ячеек. По умолчанию элемент управления MultiPage состоит из двух вкладок.

Элемент управления OptionButton (7) применяется при выборе пользователем одного варианта из нескольких. Эти элементы управления всегда группируются в диалоговом окне в наборы, содержащие не менее двух опций. Когда один элемент управления OptionButton выбран, все остальные элементы управления OptionButton текущей группы автоматически становятся неактивными. Если в пользовательском диалоговом окне содержится более одного набора элементов управления OptionButton, то каждый из таких наборов должен иметь собственное значение свойства GroupName. В противном случае все элементы управления OptionButton в диалоговом окне рассматриваются как члены одной группы. Также можно вставить элементы управления OptionButton в объект Frame, что приведет к их автоматическому группированию.

Элемент управления RefEdit (16) используется тогда, когда пользователь должен выделить диапазон ячеек на листе.

Элемент управления ScrollBar (13) в некотором смысле подобен элементу управления SpinButton. Разница заключается в том, что пользователь может перетаскивать ползунок объекта ScrollBar для изменения значения с большим приращением. Элемент управления ScrollBar рекомендуется использовать при выборе значения из большого диапазона.

Элемент управления SpinButton (14) позволяет выбрать значение после щелчка на одной из двух кнопок со стрелками. Одна из них применяется для увеличения значения, а вторая — для уменьшения. Элемент управления SpinButton часто используется совместно с элементами управления TextBox и Label, которые содержат текущее значение элемента управления SpinButton.

Элемент управления TabStrip (11) подобен элементу управления MultiPage, однако использовать его сложнее. Элемент управления TabStrip, в отличие от MultiPage, не выступает контейнером для других объектов. Как правило, элемент управления MultiPage обладает более широкими возможностями.

Элемент управления TextBox (3) позволяет пользователям вводить текст в диалоговом окне.

Элемент управления ToggleButton (8) имеет два состояния: включен и выключен. Щелчок на кнопке приводит к изменению состояния на противоположное и к изменению внешнего вида кнопки. Этот элемент управления может иметь значение True (активен) или False (неактивен). Он не относится к «стандартным» элементам управления, поэтому использование двух элементов управления OptionButton или одного CheckBox может оказаться более удачным вариантом.

Использование элементов управления на рабочем листе

Элементы управления пользовательскими диалоговыми окнами могут встраиваться в рабочий лист (без использования UserForm). Доступ к элементам управления можно получить, пройдя в Excel Разработчик –> Элементы управления –> Вставить. Для использования подобных элементов в составе рабочего листа требуется гораздо меньше усилий, чем для создания пользовательского диалогового окна. Кроме того, в данном случае можно не создавать макросы, поскольку элемент управления можно связать с ячейкой рабочего листа.

Например, если на рабочий лист вставить элемент управления CheckBox, его можно связать с нужной ячейкой, задав свойство LinkedCell. Если флажок установлен, в связанной ячейке отображается значение ИСТИНА. Если же флажок сброшен, то в связанной ячейке отображается значение ЛОЖЬ. Например, на рис. 4 переключатель «Фикс. Ставка 20%» связан с ячейкой Н15. Рисунок отображает рабочий лист, содержащий некоторые элементы управления ActiveX (см. файл activex worksheet controls.xlsx). Книга включает связанные ячейки и не содержит макросов.

Рис. 4. Элементы управления ActiveX без макросов

Элементы управления на рабочем листе могут происходить из двух источников:

  • Элементы управления формами. Эти элементы управления являются внедряемыми объектами.
  • Элементы управления ActiveX. Эти элементы управления являются подмножеством элементов, доступных в пользовательских диалоговых окнах.

Эти элементы управления работают не одинаково. После добавления элемента управления ActiveX в рабочий лист Excel переходит в режим конструктора. В этом режиме можно настраивать свойства любого элемента управления рабочего листа, добавлять или изменять процедуры обработки событий для элемента управления, а также изменять его размер или положение. Для отображения окна свойств элемента управления ActiveX воспользуйтесь командой Разработчик –> Элементы управления –> Свойства.

Для создания простых кнопок можно использовать элемент управления Button (Кнопка), который находится на панели инструментов Формы (Form). В этом случае обеспечивается возможность запуска макроса. Если же воспользоваться элементом управления CommandButton, который относится к группе элементов управления ActiveX, то после щелчка на нем вызывается связанная процедура обработки событий (например, CommandButton1_Click), которая находится в модуле кода объекта Лист (Sheet). Связать макрос с этой процедурой нельзя.

Если Excel находится в режиме конструктора, тестирование элементов управления невозможно. В этом случае нужно выйти из режима конструктора, щелкнув на кнопке Разработчик –> Элементы управления –> Режим конструктора. Эта кнопка работает, как переключатель.

Настройка элементов управления пользовательского диалогового окна

Продолжим описание использования элементов управления в UserForm. После того, как элементов управления помещен в диалоговое окно, его можно переместить и изменить размер. Можно выделить несколько элементов управления. Для этого следует удерживать нажатой клавишу <Shift> и щелкать на объектах либо обвести указателем мыши необходимые элементы управления.

В форме UserForm содержатся вертикальные и горизонтальные направляющие, которые помогают выровнять добавленные в диалоговое окно элементы управления. При добавлении или перемещении элемент управления привязывается к направляющим, что облегчает упорядочение таких элементов в окне. Если вы не используете направляющие, можете их отключить, выбрав в VBE команду Tools –> Options. В диалоговом окне Options перейдите на вкладку General и выберите соответствующие параметры в разделе Form Grid Settings.

Меню Format окна VBE предоставляет несколько команд, которые позволяют точно разместить и выровнять элементы управления в диалоговом окне. Перед использованием этих команд необходимо указать элементы управления, к которым они будут применяться (рис. 5).

Рис. 5. Выравнивание элементов в форме UserForm

Если выделено несколько элементов управления, на выделяющей рамке одного из них (обычно последнего) вместо обычных черных маркеров появляются белые. Это означает, что этот элемент управления играет роль основы, на базе которой определяются размеры и расположение других элементов управления.

Изменение свойств элементов управления

Каждый элемент управления характеризуется набором параметров, которые определяют внешний вид и поведение элемента управления. Свойства элемента управления можно изменять в следующих случаях:

  • В момент проектирования при разработке пользовательского диалогового окна. Для этого используется окно Properties.
  • В процессе выполнения, когда пользовательское диалоговое окно отображается на экране. Для этого воспользуйтесь инструкциями VBA.

Работа с окном Properties. В VBE окно Properties позволяет изменять свойства выделенного элемента управления (это может быть обычный элемент управления или сама форма UserForm, рис. 6).

Рис. 6. Окно Properties для выделенного элемента управления OptionButton

В окне Properties есть две вкладки. На вкладке Alphabetic свойства выбранного объекта отображаются в алфавитном порядке. На вкладке Categorized эти свойства сгруппированы по категориям. Обе вкладки отображают одни и те же свойства.

Для того чтобы изменить свойство, необходимо щелкнуть на нем и ввести новое значение. Некоторые свойства могут принимать только ограниченный набор допустимых значений, выбираемых из соответствующего списка. После щелчка на таком свойстве в окне Properties будет отображена кнопка со стрелкой, указывающей вниз. Щелкните на этой кнопке, чтобы выбрать значение из предложенного списка. Например, свойство TextAlign может принимать одно из следующих значений: 1 — fmTextAlignLeft, 2 — fmTextAlignCenter и 3 — fmTextAlignRight.

После выделения отдельных свойств (например, Font и Picture) рядом с ними отображается небольшая кнопка с троеточием. Щелчок на этой кнопке приводит к вызову диалогового окна настройки свойства.

Для свойства Picture элемента управления Image необходимо указать графический файл или вставить изображение из буфера обмена. В последнем случае следует сначала скопировать его в буфер обмена, а затем выбрать свойство Picture элемента управления Image и нажать комбинацию клавиш <Ctrl+V> для вставки содержимого буфера обмена. Если выделить два или более элементов управления одновременно, в окне Properties отобразятся только те свойства, которые являются общими для этих объектов.

Объекту UserForm присущ ряд свойств, значения которых можно изменять. Эти свойства применяются в качестве значений, заданных по умолчанию, для элементов управления, которые добавляются в пользовательские диалоговые окна. Например, если изменить свойство Font пользовательского диалогового окна, все добавленные в окно элементы управления будут применять этот шрифт.

Общие свойства. Каждый элемент управления имеет как собственный набор уникальных свойств, так и ряд общих свойств, присущих другим элементам управления. Например, все элементы управления имеют свойство Name и свойства, определяющие его размер и расположение на форме (Height, Width, Left и Right). Если вы собираетесь работать с элементом управления с помощью кода VBA, присвойте ему значащее имя. Например, первый элемент управления OptionButton, который добавлен в пользовательское диалоговое окно, по умолчанию получит имя ОрtionButton1. В коде ссылка на этот объект будет выглядеть следующим образом: OptionButton1.Value = True. Но если элементу управления OptionButton присвоить описательное имя (например, obLandscape), то можно использовать такой оператор: obLandscape.Value = True.

Многие пользователи предпочитают имена, которые указывают на тип объекта. В предыдущем примере был использован префикс ob, который указывает на то, что объект является элементом управления OptionButton.

Можно изменять значения свойств нескольких элементов управления одновременно. Например, вы вправе создать на форме несколько элементов управления OptionButton и выровнять их по левому краю. Для этого достаточно выделить все элементы управления OptionButton и изменить значение свойства Left в окне Properties. Все выделенные элементы управления примут новое значение свойства Left.

Чтобы получить доступ к справочной информации о свойствах различных элементов управления, щелкните на свойстве в окне Properties и нажмите клавишу <F1>.

Советы по использованию клавиатуры. Многие пользователи предпочитают перемещаться по диалоговым окнам с помощью клавиатуры. Комбинации клавиш <Таb> и <Shift+Tab> позволяют циклически переключаться между элементами управления. Чтобы удостовериться, что диалоговое окно корректно реагирует на команды с клавиатуры, обратите внимание на такие моменты: порядок просмотра элементов управления и комбинации клавиш.

Порядок просмотра определяет последовательность, в которой активизируются элементы управления после нажатия пользователем клавиши <Таb> или комбинации клавиш <Shift+Tab>. Кроме того, порядок активизации указывает, какой элемент управления по умолчанию выделяется на форме первым. Если пользователь вводит текст в элемент управления TextBox, то этот элемент считается активным. Если после этого щелкнуть на элементе управления OptionButton, то именно он станет активным. Элемент управления, назначенный первым для просмотра, будет активным в момент открытия диалогового окна.

Для того чтобы указать порядок активизации, выберите команду View –> Tab Order. Кроме того, можно щелкнуть правой кнопкой мыши на UserForm и выбрать пункт Тab Order из появившегося контекстного меню. Excel отобразит диалоговое окно Tab Order (Порядок просмотра, рис. 7).

Рис. 7. В диалоговом окне Tab Order измените порядок просмотра элементов управления

Также можно указать порядок активизации элемента управления с помощью окна Properties (см. рис. 6, самое последнее из отраженных свойств). Первый активизируемый элемент управления будет иметь свойство Tablndex = 0. Изменение значения свойства Tablndex текущero объекта приведет к изменению значений свойств Tablndex других элементов правления. Изменения вносятся автоматически. Вы можете удостовериться в том, что значения свойства Tablndex всех элементов управления не больше количества элементов управления в диалоговом окне. Если нужно удалить элемент управления из списка активизируемых объектов, то присвойте его свойству TabStop значение False.

Одни элементы управления, такие как Frame и MultiPage, служат контейнерами для других элементов управления. Элементы управления в таком контейнере имеют собственный порядок просмотра (активизации). Для установки порядка просмотра группы элементов управления OptionButtons, находящихся внутри элемента управления Frame, выделите элемент управления Frame до того, как будет выполнена команда View –> Tab Order.

Большинству элементов управления диалогового окна можно назначить комбинацию клавиш. Таким образом, пользователь получит доступ к элементу управления, нажав <Alt> и указанную клавишу. Применив свойство Accelerator в окне Properties, можно определить клавишу для активизации элемента управления.

Некоторые элементы управления, например, TextBox, лишены свойства Accelerator, поскольку не отображают значение свойства Caption. Но к таким элементам можно получить доступ с помощью клавиатуры, воспользовавшись свойством Label. Присвойте клавишу элементу управления Label и расположите его в порядке просмотра перед элементом TextBox.

Отображение пользовательского диалогового окна

Для того чтобы отобразить пользовательское диалоговое окно с помощью VBA, необходимо создать процедуру, которая вызывает метод Show объекта UserForm. Форму UserForm невозможно отобразить, не выполнив как минимум одну строку кода VBA:

Sub ShowForm()

     UserForm1.Show

End Sub

Данная процедура должна располагаться в стандартном модуле VBA, а не в модуле формы UserForm. При отображении пользовательская форма остается на экране до тех пор, пока ее не скроют. Обычно в нее добавляют элемент управления CommandButton, который запускает процедуру закрытия формы. Эта процедура либо выгружает пользовательскую форму с помощью метода Unload, либо удаляет ее с экрана с помощью метода Hide объекта UserForm.

Отображение немодальной формы. По умолчанию отображается модальная форма. Это означает, что форма должна исчезнуть с экрана прежде, чем пользователь выполнит какие-либо действия на рабочем листе (т.е. редактирование данных невозможно). Немодальную форму также можно отобразить. В этом случае вы вправе продолжать работу в Excel, не скрывая саму форму. Для отображения немодальной формы используется следующий синтаксис:

UserForm1.Show vbModeless

Тестирование пользовательского диалогового окна. Обычно в процессе разработки возникает необходимость в тестировании формы UserForm. Для этого можно воспользоваться одним из способов:

  • выполните команду Run –> Run Sub/UserForm;
  • нажмите <F5>;
  • щелкните на кнопке Run Sub/UserForm, которая находится на стандартной панели инструментов.

Выбор одного из этих методов приводит к запуску события инициализации диалогового окна. Как только диалоговое окно будет отображено в тестовом режиме, можно проверить порядок активизации объектов, а также поддержку комбинаций клавиш.

Отображение пользовательского диалогового окна на основе значения переменной. В некоторых случаях приходится выбирать, какое окно UserForm будет отображено. Если название пользовательского диалогового окна хранится в виде строковой переменной, можно воспользоваться методом Add для добавления объекта UserForm в коллекцию UserForms с последующим обращением к методу Show из коллекции UserForms. В приведенном ниже примере название объекта UserForm присваивается переменной MyForm, после чего отображается пользовательское диалоговое окно.

MyForm = «UserForm1»

UserForms.Add(MyForm).Show

Загрузка пользовательского диалогового окна. В VBA поддерживается оператор Load. Загрузка пользовательского диалогового окна приводит к сохранению объекта формы в памяти. Однако до тех пор пока не будет выполнен метод Show, форма останется невидимой для остальной части программы. Для загрузки окна UserForm1 воспользуйтесь оператором:

Load UserForm1

Если вы применяете сложное диалоговое окно, то вам может понадобиться предварительно загрузить его в память, чтобы в случае необходимости быстро отобразить его с помощью метода Show. Как правило, использовать метод Load в подобном случае не имеет смысла.

О процедурах обработки событий. Как только диалоговое окно появляется на экране, пользователь начинает с ним взаимодействовать, т.е. генерирует события. Например, щелчок на элементе управления CommandButton приводит к возникновению события Click объекта CommandButton. Вам необходимо создать процедуры (обработчики событий), которые будут выполняться при возникновении соответствующих событий.

Процедуры обработки событий находятся в модуле кода объекта UserForm. Наряду с этим процедура обработки события может вызывать другие процедуры, которые находятся в стандартном модуле VBA.

В коде VBA можно изменять свойства элементов управления, пока пользовательское диалоговое окно отображается на экране (т.е. на этапе выполнения). Например, можно назначить элементу управления ListBox процедуру, которая изменяет текст элемента управления Label при выборе элемента списка.

Закрытие пользовательского диалогового окна

Для закрытия формы UserForm1 воспользуйтесь командой: Unload UserForm1. Если же код находится в модуле кода формы UserForm, воспользуйтесь оператором: Unload Me. В этом случае ключевое слово Me применяется для идентификации пользовательской формы.

Обычно в коде VBA команда Unload выполняется только после того, как форма UserForm выполнит все свои функции. Например, форма UserForm может содержать элемент управления CommandButton, который используется в качестве кнопки ОК. Щелчок на этой кнопке приводит к выполнению заранее определенного макроса. Одна из функций макроса заключается в выгрузке формы UserForm из памяти. В результате пользовательское диалоговое окно отображается на экране до тех пор, пока макрос, содержащий оператор Unload, не завершает свою работу.

Когда форма UserForm выгружается из памяти, элементы управления, содержавшиеся на ней, возвращаются в первоначальное состояние. Другими словами, в коде нельзя обращаться к значениям, указываемым пользователем, после того как форма будет выгружена из памяти. Если значения, введенные пользователем, будут применяться позже (после выгрузки диалогового окна UserForm), то необходимо присвоить их переменной с областью действия Public, которая определена в стандартном модуле VBA. Кроме того, значение всегда можно сохранить в ячейке листа.

Окно формы UserForm автоматически выгружается из памяти после того, как пользователь щелкает на кнопке Закрыть (обозначается символом х в заголовке окна). Это действие также приводит к возникновению события QueryClose объекта UserForm, за которым следует событие Terminate пользовательского диалогового окна. Объект UserForm может использовать метод Hide. После его вызова диалоговое окно исчезает, но остается в памяти, поэтому в коде можно получить доступ к различным свойствам элементов управления:

UserForml.Hide

Если ваш код находится в модуле кода объекта UserForm, можно воспользоваться оператором:

Me.Hide

Если по какой-либо причине пользовательское диалоговое окно должно быть немедленно скрыто в процессе выполнения макроса, воспользуйтесь методом Hide в самом начале процедуры, а затем укажите команду DoEvents. Например, в следующей процедуре форма UserForm немедленно исчезнет после того, как пользователь щелкнет на кнопке CommandButton1. Последний оператор процедуры выгружает пользовательское диалоговое окно из памяти.

Private Sub CommandButton1_Click()

   Me.Hide

   Application.ScreenUpdating = True

   For r = 1 To 10000

      Cells(r, 1) = r

   Next r

   Unload Me

End Sub

В рассматриваемом примере переменной ScreenUpdating присвоено значение True, в результате чего Excel полностью скрывает окно UserForm. Если этот оператор не использовать, окно UserForm остается видимым.

Пример создания пользовательского диалогового окна

В примере представлено диалоговое окно, предназначенное для получения имени и пола пользователя. В диалоговом окне вы найдете элемент управления TextBox, используемый для ввода имени, и два элемента управления OptionButton для указания пола. Информация, полученная в диалоговом окне, заносится в пустую строку рабочего листа.

Создание пользовательской формы. Создайте рабочую книгу, содержащую только один рабочий лист. Нажмите комбинацию клавиш <Alt+F11> для активизации VBE. В окне Project выберите проект рабочей книги и выполните команду Inserts –> UserForm. Воспользуйтесь окном Properties для изменения значения свойства Caption формы UserForm на Укажите имя и пол (если окно Properties не отображается, нажмите <F4>).

Рис. 8. Создание пользовательской формы

Добавьте элемент управления Label и настройте его свойства (рис. 9):

Свойство          Значение

Accelerator        И

Caption               Имя:

Tablndex             0

Рис. 9. Пользовательская форма с элементами управления

Добавьте элемент управления TextBox и измените его свойства:

Name                   TextName

Tablndex             1

Добавьте элемент управления Frame и измените его свойства:

Caption                Пол

Tablndex             2

Добавьте элемент управления OptionButton в состав элемента Frame и измените его свойства:

Accelerator        М

Caption              Мужчина

Name                   OptionMale

Tablndex             0

Добавьте еще один элемент управления OptionButton в состав элемента Frame и измените его свойства:

Accelerator        Ж

Caption               Женщина

Name                   OptionFemale

Tablndex             1

Добавьте элемент управления CommandButton за пределами элемента Frame и измените его свойства:

Caption                OK

Default                 True

Name                   OKButton

Tablndex             3

Добавьте еще один элемент управления CommandButton и настройте его свойства:

Caption               Отмена

Default                False

Name                   CloseKButton

Tablndex             4

При создании нескольких похожих элементов управления может оказаться, что быстрее копировать существующий элемент управления, чем создавать новый. Для копирования элемента управления удерживайте нажатой клавишу <Ctrl> при перетаскивании элемента управления, что приведет к созданию копии. После этого останется изменить свойства скопированного элемента управления.

Создание кода для отображения диалогового окна. После создания элементов управления на лист необходимо добавить элемент управления ActiveX, называемый Кнопка (CommandButton). Эта кнопка будет запускать процедуру, которая предназначена для отображения формы UserForm. Для этого выполните следующие действия:

  1. Перейдите в окно Excel (например, воспользуйтесь комбинацией клавиш <Alt+F11>).
  2. Выберите команду Разработчика –> Элементы управления –> Вставить и щелкните на значке Кнопка (CommandButton), который находится в разделе Элементы ActiveX.
  3. Разместите кнопку на рабочем листе. Чтобы измените ее подпись, щелкните на кнопке правой кнопкой мыши и выберите в контекстном меню команду Объект CommandButton –> Edit. Для изменения других свойств объекта щелкните на нем правой кнопкой мыши и выберите команду Properties.
  4. Дважды щелкните на объекте CommandButton. Это приведет к активизации VBE. При этом отобразится модуль кода для листа с открытой пустой процедурой обработки событий объекта CommandButton, который расположен на рабочем листе.
  5. Введите единственный оператор в процедуру CommandButton1_Click (рис. 10). В процедуре используется метод Show объекта UserForml для отображения пользовательского диалогового окна.

Рис. 10. Процедура CommandButton1_Click вызывается после щелчка на кнопке рабочего листа

Тестирование диалогового окна. После щелчка на кнопке, находящейся на рабочем листе, ничего не произойдет. Точнее, кнопка будет выделена, но это не приведет к инициализации каких-либо действий. Причина этого заключается в том, что программа Excel по-прежнему остается в режиме конструктора, в который она переходит автоматически после добавления элемента управления ActiveX. Для выхода из режима конструктора щелкните на кнопке Разработчик –> Элементы управления –> Режим конструктора. Если же требуется изменить кнопку, снова перейдите в режим конструктора. После выхода из режима конструктора щелчок на кнопке приведет к отображению пользовательского диалогового окна.

Когда диалоговое окно будет отображено, введите произвольный текст в текстовом поле и щелкните на кнопке ОК. В результате ничего не произойдет, что совершенно естественно, так как для объекта UserForm не создано ни одной процедуры обработки событий. Для закрытия диалогового окна щелкните на крестике в его заголовке.

Добавление процедур обработки событий. Перейдите в VBE. Удостоверьтесь в том, что пользовательское окно отображено на экране, и дважды щелкните на кнопке Отмена. Активизируется окно кода для формы UserForm, а также добавляется пустая процедура CloseButton_Click. Обратите внимание, что название процедуры состоит из имени объекта, символа подчеркивания и названия обрабатываемого события. Добавьте в процедуру единственный оператор:

Private Sub CloseButton_Click()

   Unload UserForm1

End Sub

Эта процедура, которая вызывается после щелчка на кнопке Отмена, выгружает из памяти форму UserForm1.

Щелкните на значке View Object в верхней части окна Project Explorer или дважды кликните на строке UserForm1, чтобы отобразить форму UserForm1. Дважды щелкните на кнопке ОК и введите код процедуры – обработчика событий для события Click объекта OKButton:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

Private Sub OKButton_Click()

    Dim NextRow As Long

‘   Проверка активности листа Лист1

    Sheets(«Лист1»).Activate

   Проверка ввода имени

    If TextName.Text = «» Then

        MsgBox «Введите имя.»

        TextName.SetFocus

        Exit Sub

    End If

‘   Определение следующей пустой строки

    NextRow = _

      Application.WorksheetFunction.CountA(Range(«A:A»)) + 1

   Передача имени

    Cells(NextRow, 1) = TextName.Text

‘   Передача пола

    If OptionMale Then Cells(NextRow, 2) = «Мужчина»

    If OptionFemale Then Cells(NextRow, 2) = «Женщина»

   Очистка элементов управления для ввода следующей записи

    TextName.Text = «»

    TextName.SetFocus

    OptionMale = False

    OptionFemale = False

End Sub

Перейдите в Excel и щелкните на кнопке еще раз, чтобы отобразить пользовательское диалоговое окно. С его помощью можно добавлять новые имена в рабочий лист.

Процедура OKButton_Click работает следующим образом. Сначала она проверяет, активен ли лист Лист1, введено ли имя. После этого запускается функция Excel СЧЁТЗ (CountA) для определения следующей пустой ячейки в столбце А. Затем текст из текстового поля TextBox передается в определенную ячейку столбца А. С помощью операторов If определяется выделенный элемент управления OptionButton, что обеспечивает запись соответствующего текста в столбец В (пол). Далее элементы диалогового окна очищаются и окно перезапускается, чтобы обеспечить возможность введения следующей записи. Заметим, что щелчок на кнопке ОК не приведет к закрытию диалогового окна. Для завершения ввода данных (и выгрузки пользовательского диалогового окна) щелкните на кнопке Отмена.

Проверьте работоспособность комбинаций клавиш: Alt+М – активизирует мужской пол, Alt+Ж – женский. Рабочая книга с рассмотренным примером находится в файле get name and sex.xlsm.

События объекта User Form

Каждый элемент управления в форме UserForm (а также сам объект UserForm) разрабатывается для того, чтобы реагировать на определенные события. Эти события возникают в результате действий пользователя или генерируются программой Excel. Можно создать код, который будет выполняться при возникновении определенного события. Некоторые действия приводят к возникновению сразу нескольких событий. Например, щелчок на кнопке со стрелкой, направленной вверх, в элементе управления SpinButton приведет к возникновению события SpinUp и события Change. После того как пользовательское диалоговое окно будет отображено с помощью метода Show, Excel сгенерирует события Initialize и Activate объекта UserForm. В Excel также поддерживаются события, связанные с объектами Sheet (Лист), Chart (Диаграмма) и ThisWorkbook (ЭтаКнига).

Получение дополнительных сведений о событиях. Для того чтобы получить информацию о событиях, которые генерируются конкретным элементом управления, выполните следующее:

  • Добавьте элемент управления в пользовательское диалоговое окно.
  • Дважды щелкните на элементе управления, чтобы открыть модуль кода для объекта UserForm. VBE вставит пустую процедуру обработки события, принятого по умолчанию.
  • Щелкните на раскрывающемся списке в правом верхнем углу окна модуля и просмотрите полный список событий, которые поддерживаются текущим элементом управления (на рис. 11 показан список событий для элемента управления CheckBox).
  • Выберите событие из списка, и VBE создаст пустой обработчик события.

Рис. 11. Список событий для элемента управления CheckBox

Имя процедуры обработки событий включает имя объекта, который сгенерировал событие. Таким образом, если изменить имя элемента управления, придется внести соответствующие изменения и в имя процедуры обработки события. Имя процедуры не изменяется автоматически! Чтобы облегчить работу, присвойте описательные имена элементам управления до того, как приступите к созданию процедуры обработки соответствующих событий.

События объекта UserForm. Несколько событий непосредственно связано с отображением и выгрузкой объекта UserForm:

  • Происходит перед загрузкой и отображением формы UserForm. Не происходит, если объект UserForm до этого был скрыт.
  • Происходит в момент активизации объекта UserForm.
  • Происходит в момент деактивизации объекта UserForm. Не происходит при сокрытии формы UserForm.
  • Происходит перед выгрузкой объекта UserForm.
  • Происходит после выгрузки объекта UserForm.

Важно правильно выбрать подходящее событие для процедуры обработки событий, а также проанализировать порядок выполнения событий. Использование метода Show приводит к возникновению событий Initialize и Activate (в указанном порядке). Применение команды Load приводит к вызову события Initialize. Команда Unload вызывает события QueryClose и Terminate (в указанном порядке). Метод Hide не приводит к вызову каких-либо событий.

В файле userform events.xlsm описанные события перехватываются и в момент возникновения события возникает окно сообщения. Если изучение событий объекта UserForm вызывает у вас затруднения, то, проанализировав код этого примера, вы получите ответы на многие вопросы.

События элемента управления SpinButton. Для того чтобы разобраться в концепции событий, мы подробно рассмотрим события, связанные с элементом управления SpinButton (рис. 12). Файл spinbutton events.xlsm демонстрирует применение событий, генерируемых объектами SpinButton и UserForm (первый содержится во втором). Рабочая книга включает несколько процедур обработки событий — по одной для каждого события элемента управления SpinButton и объекта UserForm. Каждая из этих процедур добавляет текст в столбце А с описанием события.

Рис. 12. События элемента управления SpinButton

Пользователь может управлять объектом SpinButton с помощью мыши или (если элемент управления активен) клавиш управления курсором. Когда пользователь щелкает мышью на верхней кнопке элемента управления SpinButton, происходят следующие события: Enter (генерируется только в том случае, если элемент управления неактивен); Change; SpinUp.

Пользователь может нажать клавишу <Таb> для того, чтобы сделать активным элемент управления SpinButton. Только после этого можно использовать клавиши управления курсором для изменения значения элемента управления. Если все именно так и происходит, то события генерируются в следующем порядке: Enter; KeyDown; Change; SpinUp (или SpinDown); KeyUp.

Элемент управления SpinButton может изменяться в коде VBA, что также провоцирует возникновение соответствующих событий. Например, оператор SpinButton1.Value = 0 устанавливает свойство Value элемента управления SpinButton1 равным 0, а это приводит к возникновению события Change. Такой результат достигается только в том случае, если исходное свойство Value не равно нулю.

Вы вправе предположить, что выполнить отмену генерирования событий можно, установив свойство EnableEvents объекта Application равным False. Но это свойство поддерживается только объектами, которые являются «истинными» в Excel: Workbook, Worksheet и Chart.

Совместное использование элементов управления SpinButton и TextBox. Элемент управления SpinButton имеет свойство Value, но не может отображать значение этого свойства. В большинстве случаев требуется, чтобы пользователь мог изменить значение элемента управления SpinButton непосредственно, а не многократно щелкая на элементе управления. Эффективным решением может стать объединение элемента управления SpinButton с элементом управления TextBox, что позволяет пользователю вводить значение элемента управления SpinButton непосредственно, используя для этого поле элемента управления TextBox. Кроме того, щелчок на элементе управления SpinButton позволит изменить значение, отображаемое в элементе управления TextBox.

На рис. 13 приведен пример (см. также файл spinbutton and textbox.xlsm). Свойство Min элемента управления SpinButton имеет значение 1, а свойство Мах— значение 100. Таким образом, щелчок на одной из стрелок элемента управления SpinButton приведет к изменению значения в пределах от 1 до 100. Код, реализующий «связывание» элементов управления SpinButton и TextBox сводится к созданию процедур обработки событий, которые будут синхронизировать свойство Value элемента управления SpinButton и свойство Text элемента управления TextBox.

Рис. 13. Комбинирование элементов управления SpinButton и TextBox

Представленная процедура выполняется каждый раз при возникновении события Change элемента управления SpinButton. Таким образом, процедура выполняется тогда, когда пользователь щелкает на элементе управления SpinButton или изменяет его значение, нажав одну из клавиш управления курсором.

Private Sub SpinButton1_Change()

    TextBox1.Text = SpinButton1.Value

End Sub

Если пользователь введет значение непосредственно в элемент управления TextBox, то будет сгенерировано событие Change, после чего должен выполняться следующий код:

Private Sub TextBox1_Change()

    Dim NewVal As Integer

    NewVal = Val(TextBox1.Text)

    If NewVal >= SpinButton1.Min And _

        NewVal <= SpinButton1.Max Then _

        SpinButton1.Value = NewVal

End Sub

Эта процедура начинается с вызова функции VBA Val, которая преобразует текст элемента управления TextBox в числовое значение (если элемент управления TextBox содержит строку, то функция Val возвращает значение 0). Следующий оператор определяет, попадает ли значение в указанный диапазон допустимых значений. Если это так, то свойство Value элемента управления SpinButton устанавливается равным значению, которое введено в поле элемента управления TextBox.

Пример организован таким образом, что щелчок на кнопке ОК (которая называется OKButton) передает значение элемента управления SpinButton в активную ячейку. Процедура обработки события Click элемента управления CommandButton выглядит следующим образом:

Private Sub OKButton_Click()

   Enter the value into the active cell

    If CStr(SpinButton1.Value) = TextBox1.Text Then

        ActiveCell = SpinButton1.Value

        Unload Me

    Else

        MsgBox «Некорректная запись.», vbCritical

        TextBox1.SetFocus

        TextBox1.SelStart = 0

        TextBox1.SelLength = Len(TextBox1.Text)

    End If

End Sub

Данная процедура выполняет проверку: анализируются текст, введенный в поле элемента управления TextBox, и значения элемента управления SpinButton. Такая процедура обрабатывает ситуации неверного ввода данных. Например, если пользователь введет в поле элемента управления TextBox текст Зt, то значение элемента управления SpinButton не изменится, а результат, который помещается в активную ячейку, будет отличным от ожидаемого. Обратите внимание, что значение свойства Value элемента управления SpinButton преобразуется в строку с помощью функции CStr. Это позволяет предотвратить ошибку, которая возникает, когда числовое значение сравнивается с текстовым. Если значение элемента управления SpinButton не соответствует содержимому элемента управления TextBox, то на экране отображается специальное сообщение. Причем объект TextBox активен, а его содержимое — выделено (с помощью свойств SelStart и SelLength). Таким образом, пользователю проще исправить неправильные значения.

О свойстве Tag. Каждый объект UserForm и каждый элемент управления имеет свойство Tag. Оно не представляет конечные данные и по умолчанию не имеет значения. Свойство Tag можно использовать для хранения информации, которая будет применена в программе. Например, можно создать набор элементов управления TextBox в пользовательском диалоговом окне. От пользователя требуется ввести текст только в некоторые из них. В отдельные поля вводить текст необязательно. Можно применять свойство Tag для идентификации полей, которые нужно заполнять. В таком случае значение свойства Tag — это строка, например, Required. Поэтому при написании кода обработки введенных пользователем данных можно ссылаться на свойство Tag.

Приведенный ниже пример представляет собой функцию, которая проверяет все элементы управления TextBox объекта UserForm1 и возвращает количество пустых текстовых полей, которые требуют ввода информации.

Function EmptyCount()

   Dim ctl As Control

   EmptyCount= 0

   For Each ctl In UserFormi.Controls

      If TypeName(ctl) = «TextBox» Then

         If ctl.Tag = «Required» Then

            If ctl.Text = «» Then

               EmptyCount = EmptyCount + 1

            End If

         End If

      End If

   Next ctl

End Function

Ссылка на элементы управления пользовательского диалогового окна

При работе с элементами управления, находящимися в форме UserForm, код VBA обычно содержится в модуле кода объекта UserForm. Кроме того, на элементы управления диалогового окна можно ссылаться из модуля кода VBA общего назначения. Для выполнения этой задачи необходимо задать правильную ссылку на элемент управления, указав имя объекта UserForm. В качестве примера рассмотрим процедуру, которая введена в модуле кода VBA. Эта процедура отображает пользовательское диалоговое окно, которое называется UserForm1.

Sub GetData ()

   UserForm1.Show

End Sub

Предположим, что в диалоговом окне UserForm1 содержится текстовое поле TextBox1 и вам необходимо указать значение текстового поля по умолчанию:

Sub GetData()

   UserForm1.TextBox1.Value = «Джон Доу»

   UserForm1.Show

End Sub

Еще одним способом установки значения по умолчанию является использование события Initialize объекта UserForm. Можно написать код процедуры UserForm_Initialize, который будет располагаться в модуле кода диалогового окна:

Private Sub UserForm_Initialize()

   TextBox1.Value = «Джон Доу»

End Sub

Обратите внимание, что при обращении к элементу управления из модуля кода диалогового окна необязательно вводить в ссылку имя объекта UserForm. Подобное определение ссылок на элементы управления имеет свое преимущество: всегда можно воспользоваться средством Auto List Member, которое позволяет выбирать имена элементов управления из раскрывающегося списка.

Вместо того чтобы использовать фактическое имя объекта UserForm, предпочтительнее применить имя Me. В противном случае, если имя объекта UserForm изменится, вам придется изменять все ссылки (с его участием) в коде.

Использование коллекций элементов управления. Элементы управления пользовательских диалоговых окон образуют отдельную коллекцию. Например, следующий оператор отображает количество элементов управления в форме UserForm1:

MsgBox UserForm1.Controls.Count

В VBA не поддерживаются коллекции для каждого типа элемента управления. Например, не существует коллекции элементов управления CommandButton. Но тип элемента управления можно определить с помощью функции TypeName. Следующая процедура использует структуру For Each для циклического просмотра элементов коллекции Controls. В результате отображается количество элементов управления CommandButton, которые входят в коллекцию элементов управления объекта UserForm1 (этот код вы найдете в файле all userform controls.xlsm).

Sub CountButtons()

    Dim cbCount As Integer

    Dim ctl As Control

    cbCount = 0

    For Each ctl In UserForm1.Controls

        If TypeName(ctl) = «CommandButton» Then _

            cbCount = cbCount + 1

    Next ctl

    MsgBox cbCount

End Sub

Настройка панели инструментов Toolbox

Если объект UserForm активен в редакторе VBE, на панели Toolbox отображаются элементы управления, которые можно добавить в пользовательское диалоговое окно. Панель Toolbox изначально содержит одну вкладку. Щелкните на ней правой кнопкой мыши и в контекстном меню выберите параметр New Page (Добавить страницу). Кроме того, можно изменить текст, который отображается на вкладке. Для этого выберите параметр Rename (Переименовать) из контекстного меню.

Рекомендуется предварительно настроить элементы управления и сохранить их для дальнейшего использования. Можно, например, в форме создать элемент управления CommandButton, который настроен на выполнение роли кнопки ОК. Можно изменять параметры кнопки: Width (Ширина), Height (Высота), Caption (Подпись), Default (По умолчанию) и Name (Имя). После этого перетащите модифицированный элемент управления CommandButton на панель инструментов Toolbox. Это приведет к созданию элемента управления. Щелкните на элементе управления правой кнопкой мыши, чтобы переименовать его или изменить значок.

Также можно создать раздел панели Toolbox, в котором будет содержаться несколько элементов управления. Например, вы вправе создать два элемента управления CommandButton, которые будут представлять кнопки ОК и Отмена. Настройте их так, как это необходимо. Затем выберите обе кнопки и переместите их на панель инструментов Toolbox. Впоследствии можно использовать новый элемент управления панели Toolbox для быстрого создания необходимых кнопок.

Этот метод также применим к элементам управления, которые используются в качестве контейнера. Например, создайте элемент управления Frame и добавьте в него четыре модифицированных элемента управления OptionButton (соответствующим образом расположив их на форме). После этого перетащите элемент управления Frame на панель инструментов Toolbox, чтобы создать модифицированный элемент управления Frame.

Можно разместить модифицированные элементы управления на отдельной вкладке панели Toolbox. Таким образом, появляется возможность экспортировать вкладку панели Toolbox для совместного применения другими пользователями Excel. Для экспорта вкладки панели Toolbox щелкните на ней правой кнопкой мыши и выберите пункт меню Export Page.

Среди прилагаемых к заметке файлов находится страничный файл под именем newcontrols.pag, который включает некоторые настроенные элементы управления. Можно импортировать этот файл в качестве новой вкладки окна Toolbox. Щелкните правой кнопкой мыши на вкладке и выберите команду Import Page. В результате панель Toolbox будет как на рис. 14.

Рис. 14. В окне Toolbox появилась страница с новыми элементами управления

Добавление элементов управления ActiveX

В пользовательском диалоговом окне содержатся и другие элементы управления ActiveX, разработанные компанией Microsoft и независимыми производителями. Для того чтобы добавить дополнительные элементы управления ActiveX на панель инструментов Toolbox, щелкните правой кнопкой мыши на ней и выберите пункт Additional Controls (Дополнительные элементы управления). В результате будет отображено диалоговое окно, показанное на рис. 15.

Рис. 15. В диалоговом окне Additional Controls можно найти дополнительные элементы управления ActiveX

В диалоговом окне Additional Controls содержатся все элементы управления ActiveX, установленные в системе. Выберите элементы управления, которые необходимо добавить на панель инструментов. После этого щелкните на кнопке ОК для добавления значков каждого из выбранных элементов управления. Не все элементы управления ActiveX, установленные в системе, поддерживаются пользовательскими диалоговыми окнами. Более того, большая их часть не поддерживается, к тому же некоторые элементы управления требуют лицензии на использование в приложениях. Если лицензия отсутствует, на экране появится сообщение об ошибке.

Создание шаблонов диалоговых окон

Зачастую при создании пользовательского диалогового окна каждый раз на форму добавляются одни и те же элементы управления. Например, все пользовательские диалоговые окна имеют два элемента управления CommandButton, используемых в качестве кнопок ОК и Отмена. В предыдущем разделе рассматривались методы комбинирования элементов управления с целью получения одного элемента управления, обладающего функциями двух. Еще одной программной уловкой может служить шаблон диалогового окна, который при необходимости импортируется для последующего создания на его основе других проектов. Преимущество шаблонного подхода заключается в следующем: процедуры обработки событий сохраняются вместе с шаблоном.

Начните с создания пользовательского диалогового окна, содержащего все элементы управления и настройки, которые необходимо повторно использовать в других проектах. После этого убедитесь, что диалоговое окно выделено. Выберите команду File –> Export File (или нажмите комбинацию клавиш <Ctrl+E>). После этого на экране появится запрос на ввод имени файла. Затем для создания проекта на основе шаблона выполните команду File –> lmport File, чтобы загрузить ранее сохраненное диалоговое окно.

Имитация диалоговых окон Excel. Внешний вид и поведение диалоговых окон Windows изменяются от программы к программе. При разработке приложений для Excel рекомендуется придерживаться стиля диалоговых окон Excel. Наилучшим методом изучения эффективных способов создания диалоговых окон является повторное создание одного из стандартных диалоговых окон Excel. Например, удостоверьтесь, что вы правильно определили комбинации клавиш и активизировали элементы управления. Для создания копии одного диалогового окна Excel следует протестировать его в различных условиях. Один только анализ диалоговых окон Excel поможет улучшить познания в вопросах структуры окон и методов создания элементов управления. Со временем вы убедитесь, что невозможно повторить отдельные диалоговые окна Excel даже с помощью VBA.

[1] По материалам книги Джон Уокенбах. Excel 2010. Профессиональное программирование на VBA. – М: Диалектика, 2013. – С. 405–438.

Add the Controls | Show the Userform | Assign the Macros | Test the Userform

This chapter teaches you how to create an Excel VBA Userform. The Userform we are going to create looks as follows:

Excel VBA Userform

Add the Controls

To add the controls to the Userform, execute the following steps.

1. Open the Visual Basic Editor. If the Project Explorer is not visible, click View, Project Explorer.

2. Click Insert, Userform. If the Toolbox does not appear automatically, click View, Toolbox. Your screen should be set up as below.

Userform Screen Setup in Excel VBA

3. Add the controls listed in the table below. Once this has been completed, the result should be consistent with the picture of the Userform shown earlier. For example, create a text box control by clicking on TextBox from the Toolbox. Next, you can drag a text box on the Userform. When you arrive at the Car frame, remember to draw this frame first before you place the two option buttons in it.

4. Change the names and captions of the controls according to the table below. Names are used in the Excel VBA code. Captions are those that appear on your screen. It is good practice to change the names of controls. This will make your code easier to read. To change the names and captions of the controls, click View, Properties Window and click on each control.

Control Name Caption
Userform DinnerPlannerUserForm Dinner Planner
Text Box NameTextBox  
Text Box PhoneTextBox  
List Box CityListBox  
Combo Box DinnerComboBox  
Check Box DateCheckBox1 June 13th
Check Box DateCheckBox2 June 20th
Check Box DateCheckBox3 June 27th
Frame CarFrame Car
Option Button CarOptionButton1 Yes
Option Button CarOptionButton2 No
Text Box MoneyTextBox  
Spin Button MoneySpinButton  
Command Button OKButton OK
Command Button ClearButton Clear
Command Button CancelButton Cancel
7 Labels No need to change Name:, Phone Number:, etc.

Note: a combo box is a drop-down list from where a user can select an item or fill in his/her own choice. Only one of the option buttons can be selected.

Show the Userform

To show the Userform, place a command button on your worksheet and add the following code line:

Private Sub CommandButton1_Click()

DinnerPlannerUserForm.Show

End Sub

We are now going to create the Sub UserForm_Initialize. When you use the Show method for the Userform, this sub will automatically be executed.

1. Open the Visual Basic Editor.

2. In the Project Explorer, right click on DinnerPlannerUserForm and then click View Code.

3. Choose Userform from the left drop-down list. Choose Initialize from the right drop-down list.

4. Add the following code lines:

Private Sub UserForm_Initialize()


NameTextBox.Value = «»


PhoneTextBox.Value = «»


CityListBox.Clear


With CityListBox
    .AddItem «San Francisco»
    .AddItem «Oakland»
    .AddItem «Richmond»
End With


DinnerComboBox.Clear


With DinnerComboBox
    .AddItem «Italian»
    .AddItem «Chinese»
    .AddItem «Frites and Meat»
End With

DateCheckBox1.Value = False
DateCheckBox2.Value = False
DateCheckBox3.Value = False


CarOptionButton2.Value = True


MoneyTextBox.Value = «»


NameTextBox.SetFocus

End Sub

Explanation: text boxes are emptied, list boxes and combo boxes are filled, check boxes are unchecked, etc.

Assign the Macros

We have now created the first part of the Userform. Although it looks neat already, nothing will happen yet when we click the command buttons on the Userform.

1. Open the Visual Basic Editor.

2. In the Project Explorer, double click on DinnerPlannerUserForm.

3. Double click on the Money spin button.

4. Add the following code line:

Private Sub MoneySpinButton_Change()

MoneyTextBox.Text = MoneySpinButton.Value

End Sub

Explanation: this code line updates the text box when you use the spin button.

5. Double click on the OK button.

6. Add the following code lines:

Private Sub OKButton_Click()

Dim emptyRow As Long


Sheet1.Activate


emptyRow = WorksheetFunction.CountA(Range(«A:A»)) + 1


Cells(emptyRow, 1).Value = NameTextBox.Value
Cells(emptyRow, 2).Value = PhoneTextBox.Value
Cells(emptyRow, 3).Value = CityListBox.Value
Cells(emptyRow, 4).Value = DinnerComboBox.Value

If DateCheckBox1.Value = True Then Cells(emptyRow, 5).Value = DateCheckBox1.Caption

If DateCheckBox2.Value = True Then Cells(emptyRow, 5).Value = Cells(emptyRow, 5).Value & » » & DateCheckBox2.Caption

If DateCheckBox3.Value = True Then Cells(emptyRow, 5).Value = Cells(emptyRow, 5).Value & » » & DateCheckBox3.Caption

If CarOptionButton1.Value = True Then
    Cells(emptyRow, 6).Value = «Yes»
Else
    Cells(emptyRow, 6).Value = «No»
End If

Cells(emptyRow, 7).Value = MoneyTextBox.Value

End Sub

Explanation: first, we activate Sheet1. Next, we determine emptyRow. The variable emptyRow is the first empty row and increases every time a record is added. Finally, we transfer the information from the Userform to the specific columns of emptyRow.

7. Double click on the Clear button.

8. Add the following code line:

Private Sub ClearButton_Click()

Call UserForm_Initialize

End Sub

Explanation: this code line calls the Sub UserForm_Initialize when you click on the Clear button.

9. Double click on the Cancel Button.

10. Add the following code line:

Private Sub CancelButton_Click()

Unload Me

End Sub

Explanation: this code line closes the Userform when you click on the Cancel button.

Test the Userform

Exit the Visual Basic Editor, enter the labels shown below into row 1 and test the Userform.

Result:

Test the Userform

Содержание

  1. VBA Open or Close UserForm
  2. Open a Userform using VBA
  3. Close a Userform using VBA
  4. Initialize a Userform in VBA
  5. VBA Coding Made Easy
  6. VBA Code Examples Add-in
  7. Excel vba initialise userform
  8. Событие Initialize
  9. Событие Load
  10. Событие Activate и Deactivate
  11. Событие QueryClose
  12. Событие Unload
  13. Событие Terminate
  14. Creating VBA Userforms
  15. VBA UserForms
  16. Built in VBA UserForms
  17. Message Box
  18. Input Box
  19. Get Open Filename
  20. Excel Default Dialogs
  21. VBA Coding Made Easy
  22. Inserting a New User Form
  23. Using the Toolbox
  24. Adding an Exit Button to Your Form
  25. Adding a Label Control to a Form
  26. Adding a Text Control to the Form
  27. Initialize and Activate Events on a Form
  28. Saving Your Application and Forms
  29. Modal and Non-Modal Forms
  30. Closing a Form
  31. Enabling and Disabling Controls
  32. VBA Code Examples Add-in

VBA Open or Close UserForm

In this Article

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:

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 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.

Источник

Excel vba initialise userform

Форма в VBA это каркас приложения. Как добавлять форму в Ваш проект смотрите «Шаг 15 — Пользовательские формы». В основном события формы по ее инициализации и деинициализации разворачиваются в таком порядке:

Но форма в VBA и VB различаются. Давайте сравним:

VBA VB
UserForm_Initialize() Form_Initialize()
Нет Form_Load()
UserForm_Activate() Form_Activate()
UserForm_Deactivate() Form_Deactivate()
UserForm_QueryClose(Cancel As Integer,CloseMode As Integer) Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
нет Form_Unload(Cancel As Integer)
UserForm_Terminate() Form_Terminate()

Получается, что событие Load и Unload в VBA не обрабатываются.

Событие Initialize

Событие Initialize (Инициализация) обычно используется для подготовки к работе приложения или формы UserForm. Переменным присваиваются исходные значения, а положение или размеры элементов управления могут быть изменены для согласования с данными, заданными при инициализации. Это событие появляется до загрузки формы и ее отображения. Это событие появляется во время загрузки формы. Давайте в него напишем код:

А теперь две функции, которые вызывают Load:

В результате окно с информацией о инициализации будет на экране два раза. Так же это событие сгенерирует событие Show, так как первый раз для работы с формой ее нужно загрузить. Еще это событие может быть вызвано, если в форме определена функция общего назначения. Вызов этой функции опять приводит к загрузке формы.

А вот так можно вызвать:

Итак, событие Intialize вызывается только один раз для формы перед ее загрузкой.

Событие Load

Нет ее в VBA, а вообще в VB здесь можно что-то сделать перед выводом формы на экран.

Событие Activate и Deactivate

Событие Activate происходит, когда объект становится активным окном. А становится активным окном он может в двух случаях. Это в результате Show, когда форма становится видимой на экране и в результате получения фокуса. Событие Deactivate (Деактивизация) происходит, когда объект более не является активным окном. Эти события генерируются только при переключении между окнами одного приложения. Если вы перейдете в другую программу и вернетесь в Excel, то эти события не будут сгенерированы.

Событие QueryClose

Это событие генерируется для того, чтобы получить у пользователя разрешение на закрытие формы. В зависимости от кода возврата форма закрывается или нет.

Событие Unload

Нет его, точно так же как и Load, а вообще используется, если надо что-либо делать при выгрузке формы, например сохранить настройки пользователя.

Событие Terminate

Данное событие происходит, когда все ссылки на экземпляр объекта удаляются из памяти с помощью присвоения всем переменным, которые ссылаются на данный объект, состояния Nothing или когда последняя ссылка на объект выходит за пределы области определения. Это событие идет вслед за Unload.

Источник

Creating VBA Userforms

In this Article

This tutorial will discuss VBA UserForms.

VBA UserForms

The Userform is a very important part of programming in VBA. It allows you to build a professional looking user interface to communicate with the users of your VBA application. It also allows you to totally control the user in what they are doing to your workbook.

You can, of course, use worksheet cells to accept parameters from the user, but the userform produces a far better user experience.

By expanding the height and width of your userform to the size of the Excel window, you can make your application look like a normal Windows application, with the user being totally unaware that they are using Excel as the host.

All the normal Windows controls, such as drop downs, list boxes, tick boxes are available to you. You also have a huge range of methods, events and properties to use to enhance the user experience.

An important point is that when you display a userform that is built in or is modal, you cannot edit your code in the VBE nor access any Excel functionality. Only when the form is closed will the cursor appear in your code.

Built in VBA UserForms

Excel VBA as several built-in forms that can be used to communicate with the user.

Message Box

This is the most commonly used form in VBA. It simply displays a text message, possibly informing a user that they have entered invalid input or that a VBA process has finished running. In their simplest form, they display a text string, but you can also add an icon such as a question or exclamation mark, and give the message box a different title.

This is a basic example. There is only one button to click, and the title bar says ‘Microsoft Excel’

The code to produce this is very straightforward:

You can use different parameters to add buttons, icons, and change the title bar

This code adds in a ‘Yes’ and ‘No’ button and a question mark icon, and sets the title bar. Note that you can combine the styles of the message box by using the ‘Or’ operator

Also, when you are returning a value from a message box, the return variable must be defined as a variant or vbMsgBoxResult, and the message box statement must use brackets,

Input Box

There is a very simple input box built into VBA, although it is quite restrictive in what you can do with it. If you can, it is better to design a custom userform

You can also add a default value for the input into the parameters.

Get Open Filename

This allows you to utilize the Windows file dialog within your VBA code. It looks very impressive to the user when it is running, but it is very simple to incorporate and you automatically get all the file dialog functionality with it.

The code restricts the user to only see Excel files. Unfortunately, they could type in a non-Excel filename into the File name box, and click the open button, so you would need some code to ensure that an Excel file has been selected.

Use the ‘ChDir’ command to change the default directory to your own requirements before displaying the file dialog

Note the use of wildcards in the FileFilter parameter. The Excel files to display could be pre 2007, have macros, or be binary so the filter is ‘.xls*’.

If required, you can allow the user to select several files at once by using the MultiSelect parameter. The default is False (single select only)

The user holds down the Shift key in the file dialog to select multiple files.

The For Each loop displays the full path and name of each file selected

Excel Default Dialogs

Within Excel VBA, there is a Dialogs collection which you can use to display any standard Excel dialog. The downside is that you cannot access the parameters that the user has chosen or change the appearance of the dialog, but these dialogs can be useful in directing the user to a standard Excel function, and allowing them to choose specific parameters within the dialog.

A good example of this is to display the ‘Print’ dialog from VBA:

When you open the brackets in the Dialogs collection, you will see a list of a huge number of constants for built-in dialogs. It is worth experimenting with some of these options within your code

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!

Inserting a New User Form

You can design your own custom user forms by inserting a userform into the Visual Basic Editor (VBE)

You do this by selecting Insert | UserForm on the VBE menu bar.

Click on ‘UserForm’ and a new blank form will appear ready for you to develop on

The actual form itself (shown as ‘UserForm1’) looks quite small, but you can use the handles around it to enlarge or make it even smaller by dragging the handles with your cursor.

There is a properties window in the bottom left-hand corner of the screen. As the focus is directly on the form itself, this contains all the properties for the form specific to that form.

Note that when you start adding controls such as combo boxes and command buttons, these controls all have their own set of properties, and they can be very different in what you can do with each of them.

The properties that you see currently only apply only to the form itself.

The ‘Name’ property is the name used to define your form object within the VBA code. You may want to use something more meaningful for the object name, so that when you are reviewing your code, it is obvious which form is being used.

The ‘Name’ property will also reflect through to the ‘Project Explorer’ window in the top left-hand corner of the screen

You will want to alter the title bar of your form to something different from ‘UserForm1’, and you can do this by typing in your new text at the ‘Caption’ property

You can make a huge number of changes to how your form is seen by the user. You can alter colours, add images e.g. a corporate logo, change the position using ‘Left’ and ‘Top’, change the size using ‘Height’ and ‘Width’, change the mouse pointer, and many more

All of these properties can also be changed programmatically for any control that you have added to your form. For example, a user may select from a list box control, and you may want to disable or hide other controls based on the user’s choice

Using the Toolbox

You will notice that when you click on the form itself, a toolbox pop-up appears. If you click anywhere else e.g. the properties pane, it will disappear, but re-appear when your click on the form.

The toolbox provides the real mechanics of the form design. This enables you to add the normal Windows controls that users are familiar with to your form.

You will have notice that on the form, there is a network of dots. This is a ‘snapgrid’ so that when you add a control to the form, it will automatically align the position to the rows and columns of dots. This helps enormously with aligning your controls so that your do not get a ragged appearance of the controls

Should you click on a control, and then decide not to use it, clicking on the ‘Arrow’ icon in the top-left corner of the toolbox will change your cursor back to normal.

You can add additional controls to the toolbox by using Tools | Additional Controls on the VBE menu. There are a considerable number of these available, but depending on you Windows and Excel versions, they do not always work so some experimentation is often required.

Also, your users may not have access to some of these additional controls or be running older versions of Windows and Excel, which may cause problems. In large organizations, especially if they are global, there is no such thing as a standard build PC that you can rely on!

Adding an Exit Button to Your Form

A Command button is simple to add to the form. This looks the same way as buttons that you see in other Windows forms, usually as an ‘OK’ or ‘Cancel’ button.

Click on the Command Button icon in the toolbox. This is the second icon from the left on the bottom row of icons. See the image above. It has the letters ‘ab’ on it.

You can either hold your mouse button down and drag the control onto your form, or you can move the cursor to the form, where it will change to a ‘cross’ cursor and you can position and size your button

If you drag the control to the form, you will get the default sizing of the button. Moving the cursor to the form allows you to change the size of the button by dragging the ‘cross’ cursor across your form

Your form will now look like this:

The button will have default text as the caption, but you will want to change it to your own requirements. You can click on the text within the button (‘CommandButton1’) and this will allow you to edit the caption directly.

You can also change it in the properties window (bottom left-hand corner of screen). You will see a property called ‘Caption’ and you can edit the value for this. Change this to ‘Exit’

As with the form properties, the ‘Name’ property defines the name that will be used in your VBA code. You may want to use a name that is more meaningful and obvious within your code. You can enter this against the ‘Name’ property.

You can re-position the button by dragging it about on the form, and you can resize it by clicking on the button handles (white square boxes) and dragging the handles to make it larger or smaller

You can also re-size the button by changing the Height and Width values in the properties window

You can view your form in Excel by clicking on the green triangle in the VBE toolbar, or pressing F5

You can call your form from VBA code within a module by using the ‘Show’ method

Your user form is effectively a global object and can be called from anywhere within your code

Currently, your command button does nothing because there is no VBA code behind it. You have to write this yourself! All that can happen at the moment is that you can click on the ‘Close’ X in the top right-hand corner of your form.

To add VBA code, double click on the button on the form

This will take you to the normal VBA code window, and will show the default event of click.

You use the ‘Hide’ method to close the form, and you can also add in any other code, such as a message box to confirm to the user what has happened.

Note that the code window has two drop downs at the top. The first one allows you to select your form controls, and the second shows all the events that are available for you to add code. The obvious one for a button is the ‘Click’ event, but there are others such as ‘Double Click’ or ‘Mouse Move’

When you run your form now, the button actually does something. The form vanishes and a message box is displayed confirming that the form is closed

You can, of course, enlarge the exit code. You may wish to display another form, or take action on parameters that the user has entered on your form

Adding a Label Control to a Form

Label controls are for prompting the user as to what sort of data they need to input to a control on the form e.g. text box, drop down, etc. A label has no borders by default, but these can be added through the properties window if required.

As a control, they are read only to the user and are simply a way of putting text on the form, whether it is a bold heading, or an instruction of what to enter or choose.

To add a label, click on the ‘A’ icon in the toolbox (top row, second from left) and either double click on it or move your cursor to the form and select position and size.

Using the ‘Caption’ property in the properties window, or clicking on the label control, you can enter the text for the label control.

Note that the text will wrap according to the size of the label control, and if the string of text is too long, it will not appear completely on the form, so you need to be careful of the sizing of the label control.

Using the properties window, you can change the appearance of the label control, with different colours, fonts, back style e.g. if it overlays an image and you want it to be transparent

No code needs to be created for a label control. The main purpose is to add text to the form so that the user can see how all the other controls work

Adding a Text Control to the Form

A text control is used to allow the user to input text e.g entering a name or comments

The text control is added from the toolbox by clicking on the text control icon (top row, third from left) and double clicking or dragging the control into position on your form.

The text control is often confused with the label control, but the text control is the one for user input

The ‘Enter your name’ text is a label control, as previously described, and we now have a white text box ready for the user to type something into

Using the properties window, you can change the colours, fonts, special effects, or use password characters for your text box. Enormous flexibility is available

One very important property for a text box is the ‘MultiLine’ property. If you want the user to enter a large amount of text into the text control e.g. comments, then the ‘MultiLine’ property must be set to True.

It is a default of False which means that however big you make your text box, the text entered will stay on one continuous line and will scroll out of the text box. It will not wrap around within the box.

There is no pop-up when you right click on your text box when it is running, but CTRL+V will work for Paste, and CTRL+C will work for Cut, should the user want to cut and paste text to and from other applications

Again, you have to write your own code to deal with text that the user has typed in. You may wish to transfer it to a cell in a worksheet

You can add this code into the ‘Change’ event for the text box

You may also want to put some validation code in to check that the user is not entering rubbish which will have disastrous effects on your application

The change event is no good for this because it is called every time the user types in a new character. The user could start typing a string of text and instantly find that they have broken your validation rules before they have completed a valid text.

You use the ‘Exit’ event. This is triggered when the user moves the focus to another control on the form, which means that the user is no longer entering data.

When the user clicks on another control on the form, this code tests for either a null value in the text box, or less than 4 characters. If the test is true, then a message box with a critical icon appears to inform the user that the name is invalid, and the focus is moved back to the offending text box for the user to correct.

Note that even if the user clicks on the Exit button, the text box exit event will be performed first, so this prevents the user exiting without correcting the input

Initialize and Activate Events on a Form

When VBA first creates and builds a form it triggers an ‘Initialize’ event. However, because the form is also displayed at this point, it also triggers an ‘Activate’ event. From then onwards, every time the form appears using the ‘Show’ method or it appears as part of a hierarchy of forms, then the ‘Activate’ event is triggered, but not the ‘Initialize’ event

The ‘Initialize’ event only happens once, but the ‘Activate’ event can happen many times

On your form you may want to set up default values from the worksheet in the input controls e.g. text boxes, so that these appear on the first use of the form, but the user can overwrite the defaults and these new values will remain in place so long as the code is running

You can find the ‘Initialize’ event in the second drop down in the code window, and the userform name in the first drop down.

This code will use the value at cell A1 on ‘Sheet1’ as the default value in the text box created earlier in this article. When the form appears for the first time, the default value will appear. The user can then overwrite the default value and this will be retained. If CellA1 is blank the text box will be hidden otherwise is will be visible

The default value could also be hard coded:

You may also want to make sure that the values that the user has entered re-appear whenever the user fires up that form within that particular Excel session. VBA code can easily write the values back to cells within the workbook using the ‘Exit’ event on a control, and re-instate them using the ‘Activate’ event on the form

This code will make the user’s values persistent and also ensure that they are saved off with the rest of the workbook

Saving Your Application and Forms

When you save your Excel workbook containing your forms, all the forms and their VBA code get saved as well. However, any values that the forms hold whilst they are displayed will be lost.

It is important to write code so that when the user exits the workbook, or the form, the values are written back to cells within the workbook and so are preserved.

Modal and Non-Modal Forms

The form itself has a property ‘Show Modal’. This is set by default to True, but it can be changed to False (non-modal)

If a form is modal, it means that none of the Excel functionality can be accessed while the form is being displayed. This includes your code in the VBE window. You can view the code, but the cursor and keyboard are disabled.

In a non-modal form, you can access all the Excel functionality, including the VBE window, whilst the form is being displayed.

This is important from the point of view of controlling user behaviour

Closing a Form

However well you write your code to force the user down a certain route, they can easily circumvent it by clicking on the ‘Close’ X in the top right-hand corner of the form

You can prevent this happening by modifying the ‘QueryClose’ event of the form

The ‘QueryClose’ event is triggered when the user clicks the ‘Close’ X of the form. This code cancels the action, so the user is forced to use your ‘Exit’ button and the code that you have behind it.

Enabling and Disabling Controls

All controls on your form have a property called ‘Enabled’ which is set to True or False. If it is False, then the control is greyed out. It can be seen but cannot be used.

There is also a property called ‘Visible’ which again is set to True or False.

You can write code to either make a certain control unusable, or to make it totally invisible to the user. Using an ‘If’ statement, you can choose the circumstances when you need to do this

For example, you could disable the ‘Exit’ button initially, until the user has entered a value into the TextBox1 (name)

This code uses the form ‘Initialize’ event to disable the exit button (Command Button 1) when the form first appears and then uses the ‘Change’ event on TextBox1 (name) to enable the Exit button if something has been typed in or disable it if the box is blank.

The ‘Change’ event is triggered every time a new character is typed in or deleted from the text box. If the user tries to enter text to make the button enabled, and then deletes all the text, the button will instantly be disabled

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.

Источник

Форма в VBA это каркас приложения. Как добавлять форму в Ваш проект смотрите «Шаг 15 — Пользовательские формы». В основном события формы по ее инициализации и деинициализации разворачиваются в таком порядке:

Initialize
Load
Activate
Deactivate
QueryUnload
Unload
Terminate

Но форма в VBA и VB различаются. Давайте сравним:

VBA VB
UserForm_Initialize() Form_Initialize()
Нет Form_Load()
UserForm_Activate() Form_Activate()
UserForm_Deactivate() Form_Deactivate()
UserForm_QueryClose(Cancel As Integer,CloseMode As Integer) Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
нет Form_Unload(Cancel As Integer)
UserForm_Terminate() Form_Terminate()

Получается, что событие Load и Unload в VBA не обрабатываются.

Событие Initialize

Событие Initialize (Инициализация) обычно используется для подготовки к работе приложения или формы UserForm. Переменным присваиваются исходные значения, а положение или размеры элементов управления могут быть изменены для согласования с данными, заданными при инициализации. Это событие появляется до загрузки формы и ее отображения. Это событие появляется во время загрузки формы. Давайте в него напишем код:

Private Sub UserForm_Initialize()
MsgBox "UserForm_Initialize"
End Sub

А теперь две функции, которые вызывают Load:

Sub Test()
	Load UserForm1
	Call Test2
End Sub

Sub Test2()
	Unload UserForm1
	Load UserForm1
End Sub

В результате окно с информацией о инициализации будет на экране два раза. Так же это событие сгенерирует событие Show, так как первый раз для работы с формой ее нужно загрузить. Еще это событие может быть вызвано, если в форме определена функция общего назначения. Вызов этой функции опять приводит к загрузке формы.

Private Sub UserForm_Terminate()

End Sub

Public Sub MyMessage()
	MsgBox "MyMessage"
End Sub

А вот так можно вызвать:

Sub Test()
	UserForm1.MyMessage
End Sub

Итак, событие Intialize вызывается только один раз для формы перед ее загрузкой.

Событие Load

Нет ее в VBA, а вообще в VB здесь можно что-то сделать перед выводом формы на экран.

Событие Activate и Deactivate

Событие Activate происходит, когда объект становится активным окном. А становится активным окном он может в двух случаях. Это в результате Show, когда форма становится видимой на экране и в результате получения фокуса. Событие Deactivate (Деактивизация) происходит, когда объект более не является активным окном. Эти события генерируются только при переключении между окнами одного приложения. Если вы перейдете в другую программу и вернетесь в Excel, то эти события не будут сгенерированы.

Событие QueryClose

Это событие генерируется для того, чтобы получить у пользователя разрешение на закрытие формы. В зависимости от кода возврата форма закрывается или нет.

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
	If CloseMode <> 1 Then Cancel = 1
		UserForm1.Caption = "Close не будет работать. Выберите меня!"
	End IF	
End Sub

Событие Unload

Нет его, точно так же как и Load, а вообще используется, если надо что-либо делать при выгрузке формы, например сохранить настройки пользователя.

Событие Terminate

Данное событие происходит, когда все ссылки на экземпляр объекта удаляются из памяти с помощью присвоения всем переменным, которые ссылаются на данный объект, состояния Nothing или когда последняя ссылка на объект выходит за пределы области определения. Это событие идет вслед за Unload.

When working in Excel, you have a few ways to get information from a user and allow them to enter data. These include the following:

  • Message boxes.
  • Input boxes.
  • The GetOpenFilename method.
  • The GetSaveAsFilename method.
  • The FileDialog method.
  • Excel worksheets.
  • UserForms.

Create Excel UserForms For Data Entry In 6 Easy Steps: Tutorial and Practical ExamplesOut of the features I describe above, UserForms are one of the most powerful and efficient alternatives. Unless the information or input you need to get from the user is limited, UserForms are usually a good solution.

As explained in Mastering VBA for Microsoft Office 2016:

Dialog boxes and forms are among the most powerful and feature-packed elements of VBA.

In this UserForms Tutorial, you find all the information you need to start creating your own UserForms in Excel. This blog post is organized as follows:

  1. First section: I introduce (i) UserForms, (ii) the simple 6-step process you can use to create Excel UserForms, and (iii) the main constructs you use when designing and programming UserForms.
  2. Second section: I walk you through a step-by-step practical example of how to create a simple UserForm for data entry. In this section, you can see how the process of creating a UserForm (described in section #1) looks in practice.

This Tutorial is accompanied by an Excel workbook example that allows you to follow each of the steps I describe in the second section. You can get immediate free access to this workbook by clicking the button below.

Get immediate free access to the Excel workbook example

The following Table of Contents lists the main sections of this Tutorial.

What Is A UserForm

When working with VBA, you usually use the term “UserForm” to refer to dialog boxes.

A UserForm is an object. This object represents a window or dialog box within Excel’s User Interface. By working with the UserForm object, you can easily create custom dialog boxes. Each of these dialog boxes you create is held within an UserForm object.

You can think of a UserForm as a blank canvas. Within this canvas, you can place different elements, known as controls. Controls are, themselves, also objects. UserForm controls are the objects users work with to provide input through the UserForm.

You can find a description of the main controls you can work with further below. These controls are commonly used within Excel built-in dialog boxes. Therefore, once created, the general appearance and behavior of the custom dialog boxes you create with UserForms is usually like that of Excel’s built-in dialogs.

Why Work With UserForms

UserForms are very flexible. Therefore, you can create very complex and sophisticated UserForms that achieve a variety of different purposes and help you in different scenarios.

As I mention at the beginning of this UserForms Tutorial, there are a few ways in which you can display information and get input from a user. Some of the non-UserForm alternatives, such as Message and Input Boxes, work great in relatively simple cases. In fact, in such simple cases, Message and Input Boxes are probably more appropriate than UserForms.

There are, however, several circumstances where those alternatives aren’t powerful enough for your purposes. Consider, for example, the following scenarios or considerations:

  • A user should make choices or decisions that can’t be adequately captured by the limited controls available in Message or Input boxes.
  • The macro requires the user to make several different data entries.
  • The user input you require is too specialized or complex for Message or Input boxes.
  • You want to restrict the choices users can make or the data they can enter by establishing sophisticated or complex data validation and controlling rules.
  • You want to ensure that users can easily navigate a data entry form without confusion.

More broadly, and in the words of Excel MVP Tom Urtis (in the Excel VBA 24-Hour Trainer):

UserForms enable you to interact with your users in ways that you can’t when using standard Message Boxes, InputBoxes, or controls embedded onto your worksheet.

This doesn’t mean that UserForms and, more generally, ActiveX controls are perfect or that they should be your go-to choice. There are some downsides to UserForms. For example, as explained by Excel MVP Jordan Goldmeier in Advanced Excel Essentials, UserForms can sometimes act unpredictably. Jordan also explains how differences in factors such as “internal settings and hardware” may result in UserForms appearing “different across different computers”.

How To Create An Excel UserForm: Overview

At a basic level, you can create a UserForm in the following 6 simple steps:

  1. Insert a UserForm.
  2. Add controls to the UserForm.
  3. Move or resize the added UserForm controls, as required.
  4. Customize the UserForm or its controls.
  5. Assign VBA code to the UserForm.
  6. Display or load the UserForm.
  7. Close or hide the UserForm.

How To Insert A New UserForm

You can insert a UserForm in the following 3 easy steps:

  1. Go to the Visual Basic Editor by, for example, using the “Alt + F11” keyboard shortcut.
  2. Go to the Project Explorer, and right-click on the workbook (Project) where you want to insert the UserForm.

    VBE and Project Explorer and Project

  3. In the context menu displayed by the VBE, go to Insert > UserForm.

    Right-click and Insert and UserForm

As an alternative to steps #2 and #3 above, you can proceed as follows:

  1. Select the Project where you want to insert the UserForm.

    Project Explorer and Project

  2. Do one of the following:
    • Click on the Insert UserForm button in the toolbar.

      Toolbar and Insert UserForm button

    • Go to Insert > UserForm.

      VBE and Insert and UserForm

Once you complete the process above, Excel the inserts the UserForm. By default, the UserForm contains an empty dialog box. Notice that, in addition to displaying the UserForm window on the right side of the screen, the VBE adds the following items to the Project Explorer:

  • A Forms node. If the VBA Project you’re working on already contains a Forms node, the VBE doesn’t add it again.
  • A new UserForm. This UserForm appears within the Forms collection.

Forms and UserForm in Project Explorer, new UserForm

A UserForm object can hold a single dialog box. Therefore, you must create and insert a new UserForm for each dialog box you want to create. However, you have significant flexibility regarding the amount of UserForms you can store within a single workbook.

Usually, in addition to displaying the new UserForm, the VBE shows a floating window known as the Toolbox. The Toolbox is, also, usually displayed when you activate a UserForm.

VBE and UserForm Toolbox

This Toolbox is the feature you use to add controls to the UserForm you just created. You can learn more about it in the appropriate section below.

If your Visual Basic Editor doesn’t display the Toolbox, do either of the following:

  • Click on the Toolbox button in the VBE toolbar.

    Toolbar and Toolbox button

  • Go to the View > Toolbox.

    VBE and View and Toolbox

How To Add Controls To A UserForm With The Toolbox

You can add a control to a UserForm in 3 simple steps:

  1. Select a control in the Toolbox.

    For example, in the following image, I select a Label.

    Toolbox and Label

  2. Click on the UserForm, in the place where you want to add the control. This results in the created control having its default size.

    Click on UserForm

    Alternatively, you can click-and-drag within the UserForm. This allows you to specify the size of the control.

    Click-and-drag to add control to UserForm

  3. If necessary, you can move or resize the control, using commonly-used methods. You can find further details about some of these methods below.

If you need to add the same control several times to a single UserForm, you can take advantage of a shortcut by proceeding as follows:

  1. Double-click on the control within the Toolbox.

    Double-click on Toolbox control

  2. Click on the UserForm, where you want to add the control.
  3. Repeat step #2 as required until you’ve added the number of controls you need.

    Add several controls to same UserForm

  4. Click on the Select Objects command in the Toolbox to restore the mouse pointer to Selection mode.

    Toolbox and Select Objects command

In the example above, I work with a Label. This is only 1 of the different controls you can add to your UserForms. To better understand the different controls you can add, let’s explore…

The Toolbox

The Toolbox is a relatively simple floating window that allows you to add ActiveX controls to your UserForms. You work with the Toolbox because the VBE’s menu doesn’t have commands that allow you to add UserForm controls.

It contains a single tab (Controls) and 16 icons.

UserForm Toolbox

Out of the 16 icons that appear in the Toolbox, 15 are controls you can insert in your UserForms. You can divide these controls in the following groups:

  1. Controls that influence the appearance of your UserForm.
  2. Controls that allow users to enter data, make selections or issue a command.

The remaining control is Select Objects. As indicated by its name, Select Objects allows you to select and manipulate the different elements of your UserForm.

Toolbox and Select Objects

You rarely need to click on the Select Objects control. This is because Select Objects is the default control and the mouse pointer usually returns to this mode automatically. According to author Richard Mansfield (in Mastering VBA for Microsoft Office 2016), there are 2 common cases where you need to click on the Select Objects control:

  1. If you select a control but change your mind before using it.
  2. If you add the same control several times to a single UserForm by using the technique I describe in the previous section (double-clicking on the control within the Toolbox).

In both cases, you restore the mouse pointer to Selection mode by clicking on Select Objects.

Which controls you choose to add to a UserForm depend on the objective you’re trying to achieve. The following sections briefly introduce the 15 controls that are available in the Toolbox.

Group #1: Controls That Influence The Appearance Of Your UserForm

This group of control allows you to customize your UserForm.

  1. Label: Displays a text label. You commonly use labels to (i) identify a section of the UserForm, or (ii) display information.

    UserForm Label

  2. Frame: Displays a frame where you can enclose other controls. This grouping can be for either aesthetical or logical purposes. You can, for example, use Frames to (i) group several controls that are logically related, or (ii) distinguish between different sets of OptionButton controls. Additionally, Frames allow you to separate different groups of OptionButtons (described in Group #2 below)).

    UserForm Frame

  3. MultiPage: Displays a container with tabs. This is the control you usually use to create dialog boxes with tabs.

    UserForm MultiPage

  4. TabStrip: Displays several tabs within the dialog box.

    UserForm TabStrip

  5. Image: Displays an image.

    UserForm Image

    If you choose to display an Image, consider that Images are stored within the workbook you’re using. Therefore, Images can have a substantial influence on the size of your workbook. Usually, you want to avoid using (i) too many Images, or (ii) Images that are too large.

Group #2: Controls That Allow Users To Enter Data, Make Selections Or Issue A Command

This group of controls allow the users of your UserForm to (i) enter data, (ii) make selections, or (iii) issue commands.

  1. TextBox: Displays an input field. Allows users to enter text or values.

    UserForm Textbox

  2. ComboBox: Displays a drop-down list, where only 1 item is visible at a given time. Users can use the drop-down list to select an item. Additionally, users can normally make entries different from those within the list. In other words, you can think of a ComboBox as a combination of a TextBox and a ListBox.

    UserForm ComboBox

  3. ListBox: Displays a list. Users can select 1 or more items from the list, depending on the setting you specify for the ListBox.MultiSelect property.

    UserForm ListBox

  4. CheckBox: Displays a checkbox. Allows users to specify a binary choice: True or False. If the checkbox is checked, its value is True. If the checkbox isn’t checked, its value is False.

    UserForm CheckBox

  5. OptionButton: Usually used in groups. When you have a set of OptionButtons, users can generally select only 1. When a user selects 1 option, Excel automatically de-selects the other options. This ensures that users only select a single option from the group.

    UserForm OptionButton

    You can use Frames (describe in Group #1 above) to separate OptionButtons. OptionButtons within a Frame are treated as a single group, separate from other groups of OptionButtons. This allows you to use several sets of OptionButtons, where the user can select an option in each group. Alternatively, you can work with the OptionButton.GroupName property.

    In both cases, the idea is the same: grouped OptionButtons are mutually exclusive. Therefore, a user can select 1 option from within the group. If you don’t explicitly group OptionButtons using 1 of the methods I describe above, Excel treats all the OptionButtons in the UserForm as the same group.

  6. ToggleButton: Displays a toggle button. Users can use this button to toggle between 2 states: True and False. If the ToggleButton is pressed, its value is True. If the ToggleButton isn’t pressed, its value is False. The appearance of a ToggleButton depends on the current state.

    UserForm ToggleButton

  7. CommandButton: Displays a button, which users can click. When the user clicks a button, your VBA Application usually performs an action.

    Command button

  8. ScrollBar: Displays a scrollbar. Users can drag the scrollbar to specify a value.

    UserForm CommandButton

  9. SpinButton: Displays a spinner. Allows users to modify a value by clicking on 1 out of 2 arrow buttons.

    You can have SpinButtons with either vertical or horizontal orientation. If the spinner is vertically-oriented, the up arrow increases the value and the down arrow decreases it. If the spinner is horizontal, the right arrow increases and the down arrow decreases the value.

    UserForm SpinButton

  10. RefEdit: Displays a reference edit control, which is a cell range input field. Users can use this control to enter or select a cell or range of cells.

    UserForm RefEdit

You’re, strictly speaking, not limited to using the built-in controls within the Toolbox or Excel. This is because you can customize the Toolbox and use other ActiveX controls. However, in this UserForms Tutorial, I introduce only the controls that appear within the Toolbox. Those are the most commonly-used.

How To Select, Move Or Resize UserForm Controls And UserForms

Once you’ve added a control to a UserForm, you can easily move or resize it. You generally do this with the mouse. The following are some of the most commonly-used methods to move or resize controls or the UserForm itself:

  • Select several controls by either (i) pressing and holding the Ctrl key while you select controls with the mouse, (ii) pressing and holding the Shift key while you select controls with the mouse, or (iii) clicking-and-dragging your mouse to enclose the group of controls you want to select.

    Select several UserForm controls

  • Move a control by dragging-and-dropping it with your mouse.

    Drag-and-drop UserForm control

  • Resize a control by selecting and dragging the sizing handles on the control’s border.

    UserForm control sizing handles

    The UserForm itself also has sizing handles, which you can use to resize the UserForm.

    UserForm sizing handles

The UserForm Grid

When you’re working with a UserForm, the VBE usually displays dots forming a grid.

UserForm grid

The purpose of such grid is to help you align all the controls within the UserForm. Depending on your settings, the controls you work with snap automatically to the grid.

The grid is, in any case, not visible in the actual UserForm displayed to the users.

You can specify 3 settings related to this dot grid:

  1. Whether the grid is visible or not.
  2. The size of the grid elements.
  3. Whether controls snap to the grid or not.

You determine these settings from the General tab of the Options dialog. You can get to this tab in the following 2 easy steps:

  1. Go to Tools > Options.

    Tools and Options

  2. Within the Options dialog, go to the General tab.

    Options dialog box and General

The settings that apply to the grid are grouped under Form Grid Settings. Within this group of settings, you find the following:

  1. Show Grid: Allows you to specify whether the grid is shown (or not shown). You can set this by checking (or unchecking) the box to the left of “Show Grid”.

    If the checkbox is selected, the grid is displayed. If the checkbox isn’t selected, the grid isn’t displayed.

    Options and General and Show Grid

  2. Grid Units: Allows you to set the size of the individual grid elements (the distance between the grid dots). You do this by specifying the width and height, in points, within the Width and Height fields. The default value is 6 points for both height and width. The larger the values, the bigger the separation between grid dots.

    Options and General and Grid Units

  3. Align Controls to Grid: Allows you to specify whether controls align or snap to the grid. If you want the controls to snap to grid, select the checkbox next to the left of “Align Controls to Grid”. If the checkbox isn’t selected, controls don’t align to the grid.

    Options and General and Align Controls to Grid

Once you’ve selected the settings you want to use, click the OK button to confirm your selections.

Options dialog box and OK

The Format Menu Or UserForm Toolbar

You can use the commands in the Format menu or the UserForm toolbar to arrange the controls within a UserForm.

I describe the main commands below. First, let’s look at the different ways you can access them:

How To Access The Commands In The Format Menu Or UserForm Toolbar

You can access the commands within the Format Menu or UserForm toolbar using any of the following 3 methods:

  1. Through the Format menu, in the following 2 easy steps:
    1. Select the control(s) you want to manipulate.
    2. Go to the Format menu and select the command you want to apply.

      Select UserForm controls. Format and Command

  2. Through the UserForm toolbar, in the following 3 simple steps:
    1. If you can’t see the UserForm toolbar, make it visible by going to View > Toolbars > UserForm.

      View and Toolbars and UserForm

    2. Select the control(s) you want to work with.
    3. Click on the appropriate button in the UserForm toolbar.

      Select UserForm controls and use UserForm toolbar

  3. Through a context menu in the following 2 easy steps:
    1. Select the control(s) and right-click on them.
    2. Select the command you want to apply from the context menu.

      Right-click UserForm controls and command

The available commands may vary slightly, depending on the context you’re in and which of the 3 methods above you use to access them.

The order in which you select the controls matters:

When resizing or moving controls, the VBE must use 1 of them as a reference. You can identify which controls are moved or resized, and which control is used as reference, based on the color of their sizing handles. Controls that are resized or moved have black sizing handles. The control that is used as reference has white sizing handles.

Reference and resized or moved controls

The reference control is usually the last one you click on prior to executing the command. This allows you to choose the reference control after you’ve selected all the controls you want to manipulate.

Commands In The Format Menu Or UserForm Toolbar

The following are the 11 options displayed by the VBE when you expand the Format menu. Several of these commands are also available through the UserForm toolbar or a context menu, as I explain above.

  1. Align: Use this to align several controls. You can choose any of the following alignment options:

    Format and Align and Lefts, Centers, Rights, Tops, Middles, Bottoms, to Grid

    • Lefts: Aligns the selected controls to the left border of the reference control.
    • Centers: Aligns the (horizontal) center of the selected controls.
    • Rights: Aligns the selected controls to the right border of the reference control.
    • Tops: Aligns the selected controls to the top border of the reference control.
    • Middles: Aligns the (vertical) center of the selected controls.
    • Bottoms: Aligns the selected controls to the bottom border of the reference control.
    • To Grid: Snaps the selected control(s) to the grid.
  2. Make Same Size: Allows you to resize the selected controls so that they have the same dimensions. You can choose from within the following resizing options:

    Format and Make Same Size and  Width, Height, Both

    • Width: Resizes the selected controls to be of the same width as the reference control. The height of the controls doesn’t change.
    • Height: Resizes the selected controls to be of the same height as the reference control. The width of the controls isn’t changed.
    • Both: Resizes the selected controls to have the same height and same width.
  3. Size to Fit: Autofits the selected control(s). In other words, the control(s) are resized per their contents.

    Format and Size to Fit

  4. Size to Grid: Resizes the selected control(s) to the nearest grid points.

    Format and Size to Grid

  5. Horizontal Spacing: You can use these settings to specify the horizontal spacing between the selected controls. Choose from the following spacing options:

    Format and Horizontal Spacing and Make Equal, Increase, Decrease, Remove

    • Make Equal: Makes the horizontal spaces between the selected controls equal.
    • Increase: Increases the horizontal spacing between the controls.
    • Decrease: Decreases the horizontal spacing between the controls.
    • Remove: Removes the horizontal spacing between the controls.
  6. Vertical Spacing: Allows you to specify the vertical spacing between the selected controls. You can use the same options as when working with Horizontal Spacing (above).

    Format and Vertical Spacing and Make Equal, Increase, Decrease, Remove

    • Make Equal: Makes the vertical spaces between the selected controls equal.
    • Increase: Increases the vertical spacing between the controls.
    • Decrease: Decreases the vertical spacing between the controls.
    • Remove: Removes the vertical spacing between the controls.
  7. Center in Form: Allows you to center the selected control(s) horizontally or vertically within the UserForm.

    Format and Center in Form and Horizontally, Vertically

    • Horizontally.
    • Vertically.
  8. Arrange Buttons: You can use these settings to arrange CommandButtons either of the following ways:

    Format and Arrange Buttons and Bottom, Right

    • Bottom: Arranges the selected CommandButton(s) on the bottom of the UserForm.
    • Right: Arranges the selected CommandButton(s) on the right side of the UserForm.
  9. Group: Groups the selected controls.

    Format and Group

  10. Ungroup: Ungroups controls that were previously grouped (for example, by using #9 above).

    Format and Ungroup

  11. Order: Allows you to order a stack of controls from the front to the back. You can choose any of the following commands:

    Format and Order and Bring to Front, Send to Back, Bring Forward, Send Backward

    • Bring to Front: Brings the selected control to the front of the stack.
    • Send to Back: Sends the selected control to the back of the stack.
    • Bring Forward: Brings the selected control 1 step forward.
    • Send Backward: Sends the selected control 1 step backward.

The UserForm toolbar contains several of the commands I list above. Additionally, it contains a Zoom drop-down list. This zoom feature allows you to zoom into or out of the UserForm controls. In other words, controls are resized per the percentage you choose.

UserForm toolbar and Zoom

How To Customize A UserForm Or Its Controls

You customize a UserForm or its controls (all of which are objects) by modifying their properties. You can specify these properties in 3 ways:

  1. Programmatically, using VBA code.

    You usually rely on this option if you want to set properties at runtime. This means that you can use VBA to set properties when the UserForm is displayed.

  2. Manually, by manipulating the object within the UserForm window.

    This applies only to some properties, particularly those related to size and position such as Height, Width, Left and Top. You can learn more about this topic by reading the previous section.

  3. Manually, using the Properties Window of the VBE.

    This is the option you generally use while designing your UserForm within the VBE and is the focus of this section. The properties you set through the Properties Window are usually static (vs. dynamic) and, therefore, you rarely use VBA code (#1 above) to modify them later.

While designing a UserForm within the VBE, you can change a property through the Properties Window in the following 3 easy steps:

  1. Within the UserForm window, select (i) the control you want to customize, or (ii) the UserForm itself.

    Selected UserForm

  2. Go to the Properties Window and select the property you want to modify.

    Property to modify in Properties Window

  3. Set the new property value.
    Enter new property value

In this UserForms Tutorial, I focus on the basics of creating and designing UserForms. Therefore, I only explain how to use the Properties Window of the VBE for these purposes. In the UserForm example that appears in the second section of this blog post, you can find some basic examples of how to use VBA to set the properties of a UserForm or its controls programmatically.

UserForm Or Control Properties Vs. Other VBA Properties

Objects within the Excel VBA Object Model have properties. Properties are the attributes, characteristics or qualities that you can use to describe an object.

The UserForm object and the controls within the UserForm itself are also objects and, therefore, also have properties. The basic purpose of these properties doesn’t change: they allow you to describe the attributes, characteristics or qualities of an object.

There’s, however, an important difference between the way you usually work with properties (i) within VBA, and (ii) when dealing with UserForms and UserForm controls.

When you create macros, you usually use VBA code to either return (read) or modify (write) the current property setting. When you work with UserForms, you can also use VBA. However, you can also modify UserForm and UserForm control properties in a different way:

By using…

The Properties Window

The Properties Window is commonly displayed on the lower left corner of the VBE, although this varies. You can get the VBE to show the Properties Window by, for example, using the “F4” keyboard shortcut.

Properties Window in VBE

The Properties Window shows the properties of the currently-selected object. If your current selection includes more than 1 object, the Properties Window lists the properties that are common to the selected objects.

Alternatively, you can use the drop-down list at the top of the Properties Window to specify the object whose properties you want to see.

Drop-down list at top of Properties Window

Objects have different properties, although some properties are commonly-shared by different objects. Therefore, the appearance of the Properties Window changes depending on the object you select.

Additionally, the Properties Window can display the properties of the same object organized per 2 different criteria. You select the organization criteria by choosing 1 of the 2 tabs the Properties Window has:

  1. Alphabetic: Organizes the properties in alphabetical order.

    Alphabetic tab of Properties Window

  2. Categorized: Organizes the properties in categories.

    Categorized tab of Properties Window

Regardless of the categorization criteria you use, the properties don’t change. The Properties Window lists an object’s properties and those properties don’t change just because they’re listed in a different order.

How To Modify Properties With The Properties Window

The Properties Window usually contains 2 columns. The left column lists the name of the properties. The right column shows the current property setting.

Columns in Properties Window

Therefore, once you’ve selected the object you want to work with, you can proceed as follows:

  1. Identify the property you want to modify using the names that appear in the left column of the Properties Window.

    Property names in Properties Window

  2. Double-click the right column of the Properties Window and enter the new property setting.

    Property values in Properties Window

    You can generally enter a new property value in 1 of 3 ways:

    1. By typing the new setting.

      Enter new property value

    2. By selecting a setting from a pre-set list of values. Properties that can take a limited list of values have a drop-down list in the Properties Window. You can easily identify such properties because, when you select one, the VBE displays a drop-down button.

      Set property with drop-down list

      When working with these properties you can either (i) click on the drop-down and select a value, or (ii) double-click the property name or property value to cycle through the available values.

    3. By opening a dialog box. You can identify the properties whose setting you specify through a dialog box because, when selected, the VBE displays a button with an ellipsis (…).

      Set property with dialog box

You can modify the properties of several objects at the same time. To do this, select all the objects whose property you want to modify prior to executing the 2-step process I describe above. When you select several objects at the same time, the Properties Window displays those properties that are common to the selection.

Properties window with several controls selected

Some of the properties of the UserForm are default settings for new controls. In other words, the new controls you add to the UserForm are influenced by that property setting. Therefore, if you modify those default control settings:

  • Controls added after the property modification use the new property setting, but…
  • Controls added prior to the property modification remain unchanged and don’t use the new property setting.

Why Modify The Name Property Of Your UserForms Or UserForm Controls

Each object has its own properties. These properties generally vary from object to object. There are, however, some properties that are common to several different objects. Commonly-used properties include Name, Width, Height, Left, Right, Value and Caption. In fact, UserForms and all UserForm controls have the Name property.

In practice, you usually modify just a few properties through the Properties Window. Name is 1 such property that you usually set through the Properties Window.

Every time you add a UserForm to a Project, the Visual Basic Editor assigns a default name:

UserForm#

“#” is an integer that starts at 1 and increases sequentially. Therefore, the first UserForm you add is UserForm1. The second is UserForm2. The third is UserForm3. And so on…

This may look familiar. Excel uses similar naming conventions for workbooks, worksheets, and regular VBA modules (among others).

That same rule applies to the controls within a UserForm. For example, if you’re working with Label controls, the first Label is named Label1. The second is Label 2. And so on…

You can find the name of a UserForm or UserForm control by checking its Name property in the Properties Window. This property is important:

You use the Name property of a UserForm or a UserForm control to refer to it when creating your VBA code. Since you may use these names relatively often, you may prefer using names that are more descriptive and meaningful than the default ones.

Notice, additionally, that any time you change the Name property of a UserForm or a UserForm control, you may have to go back to your VBA code to update the object references. To avoid this, you may prefer modifying the names of your UserForms and UserForm controls as soon as possible after creating them and prior to writing your VBA code.

How To Name UserForms Or UserForm Controls

Several of the general naming rules, such as those that apply to properties and Sub procedures, are also applicable to UserForms and UserForm controls. The following are the main rules you may want to consider when setting the names of your UserForm and UserForm controls:

  • The maximum name length is 40 characters.
  • The first character must be a letter.
  • Characters, other than the first, can include letters, numbers and underscores (_).
  • Names can’t include spaces ( ), periods (.), mathematical operators (such as +, -, /, * or ^), comparison operators (for example, >, < or =), or certain punctuation characters (such as @, #, $, %, &, and !).
  • Names must be unique within the object’s scope. Notice that the scope of a UserForm is different from the scope of a UserForm control.
    • The scope of a UserForm is, generally, the whole VBA Project. Therefore, UserForm names must be unique within the workbook.
    • The scope of a UserForm control is, generally, the UserForm where its located. Therefore, UserForm control names must be unique within the UserForm.

A common naming convention for UserForms and UserForm controls involves adding a control identifier at the beginning of the name. You do this by adding a 3-letter prefix to the control name. The following table lists some commonly used prefixes described in, among others, Excel 2016 Power Programming with VBA and Mastering VBA for Microsoft Office 2016.

UserForm Control Prefix
CheckBox chk
ComboBox cbx or cmb
CommandButton cmd
Frame fra
Image img
Label lbl
ListBox lst or lbx
MultiPage mpg
OptionButton opt
RefEdit ref
ScrollBar scr
SpinButton spb
TabStrip tab or tbs
TextBox txt or tbx
ToggleButton tgb
UserForm frm or uf

How To Remove Controls From A UserForm

You can easily delete controls from a UserForm using either of the following 2 methods:

  1. Select the control and go to Edit > Delete, or press the Delete key.

    Select control, Edit and Delete

  2. Right-click on the control and select Delete from the context menu.

    Right-click and Delete

How To Assign VBA Code To A UserForm

Once you complete the design of your UserForm, you must create the macros that power it and respond to the user’s actions. You can create and assign macros to a UserForm in the following 2 easy steps:

  1. Go to the Code window of the UserForm by, for example, using the “F7” keyboard shortcut.
  2. Enter the appropriate VBA code within this Code window.

This section focuses on the macros that you attach or assign to the UserForm. This is different from the macros responsible for displaying the UserForm in the first place.

In other words, when working with UserForms, you deal with (at least) 2 different types of Sub procedures:

  1. A Sub procedure that displays the UserForm. You can read more about this topic in a section further below.
  2. 1 or more event-handler procedures, which are attached to the UserForm. This is the topic of this section.

Additional considerations apply to the VBA code you use to close the UserForm, even though this code is commonly attached to the UserForm. I explain how you can close or hide a UserForm further below.

What Is A UserForm Code Window And Why You Work With It

When working with UserForms, you create event-handler procedures that are stored within the code module of the appropriate UserForm object. In other words:

  • UserForms are class objects have a code module. This is like what occurs with other object classes, such as Worksheets or Workbooks.
  • You use this module to store the procedures to be executed when a user works with the UserForm.
  • The procedures you assign to UserForms are event-handler procedures. In other words, these procedures are executed when an event occurs. In the case of UserForms, these events are the consequence of the user interacting with the UserForm.

Notice the difference between the following:

  • The event-handler procedures which are executed when a user works with the UserForm. These event-handler procedures are stored within the UserForm Code window.
  • The procedure(s) that control the display of the UserForm. These procedures are usually stored within a regular module, and never within the UserForm Code module. You can read more about how to display a UserForm further below.

How To Toggle Between The Code And UserForm Windows

Within the VBE, you work with 2 UserForm windows or modules:

  1. The UserForm window: You use this module to manipulate and customize the UserForm and its controls.

    UserForm window in VBE

  2. The Code window: You use this module to create and store the event-handler procedures associated with the UserForm.

    UserForm Code window

You can toggle back and forth between these 2 windows with any of the 3 following features:

  1. The “F7” and “Shift + F7” keyboard shortcuts:
    • “F7” displays the Code window.
    • “Shift + F7” displays the UserForm window.
  2. The View Code and View Object commands within the View menu.
    • Go to View > Code to see the Code window.

      View and Code

    • Go to View > Object to see the UserForm window.

      View and Object

  3. The context menu displayed when you right-click on the UserForm within the Project Explorer.

    Right-click and View Code, View Object

    • Right-click the UserForm and select View Code to go to the Code window.
    • Right-click the UserForm and select View Object to go to the UserForm window.

If you want to go to the UserForm window, you can generally double-click the UserForm within the Project Explorer.

Double-click UserForm in Project Explorer

Why UserForms Work With Event-Handler Procedures

When working with UserForms, your main purpose is usually to allow users to enter information or provide other input for your macros. Therefore, your code must be able to respond to what the user does with the UserForm. You do this by relying on events.

From a broad perspective, an event is something that happens while you’re working with Excel. In the case of UserForms, these are events that occur within the UserForm itself. Once the appropriate event occurs, your event-handler procedure is executed. This way, your VBA application can respond to the user’s actions.

When working with UserForms, your code must respond to both UserForm and control events. The events you can work with vary depending on the UserForm control. In other words, UserForm controls have different associated events.

How To Create Event-Handler Procedures For UserForms

The general principles that apply to event-handler procedures, a topic I cover in this blog post, are applicable to the event-handler procedures you create to deal with UserForms.

The following are 3 of these principles, as they apply to UserForms:

  1. The basic structure of the names of event-handler procedures is composed of the following 3 (or 4) items:
    1. The UserForm or UserForm control.
    2. An underscore (_).
    3. The event that triggers the event-handler procedure.
    4. In some cases, an argument list.
  2. If you don’t enter the appropriate declaration statement, following the structure I describe in #1 above, the procedure doesn’t work.
  3. However, you don’t have to learn the exact names or declaration statements for event-handler procedures. You can get the VBE to enter the appropriate declaration statement by using either of the 2 processes I describe in the following section.

How To Enter The Declaration Statement For An Event-Handler Procedure

You can get the VBE to enter the appropriate declaration statement for an event-handler procedure in the following 9 easy steps:

  1. Go to the UserForm Code window for the appropriate UserForm.

    UserForm Code window

  2. Click on the Object drop-down list that appears at the top left side of the UserForm Code window. This drop-down is labeled “(General)”.

    (General) drop-down list

    When you expand this drop-down list, the VBE displays the UserForm and all the UserForm controls within the relevant UserForm.

    Expanded Object drop-down list

  3. Select the object you want to work with.

    In the screenshot below, I select the UserForm.

    Object drop-down list and UserForm

  4. Once you select an object, the VBE includes the declaration and End statements for a Sub procedure. This Sub procedure corresponds to the default event of the object you chose.

    In the screenshot below, the VBE enters the opening and closing statements for the Sub procedure triggered by the Click event of the UserForm object (Private Sub UserForm_Click()).

    Private Sub UserForm_Click()

  5. If you want to work with the default event of the chosen object, you can start working on your Sub procedure. Use the statements entered by the VBE in step #4 above as a basis.

    If you want to work with another event, proceed to step #6.

  6. Click on the Procedure drop-down list, which appears at the top right side of the UserForm Code window. The label of this drop-down is “(Declarations)”.

    (Declarations) drop-down list

    The expanded drop-down list includes all the events that apply to the object you’re working with.

    Expanded Procedure drop-down list

  7. Select the event you want to work with.

    In the screenshot below, I select the Initialize event.

    Initialize event selection

  8. Once you select an event, the VBE enters new declaration and End statements for a Sub procedure. This Sub procedure corresponds to your chosen object and event.

    Use these statements as the basis to code your event-handler procedure.

    Private Sub UserForm_Initialize

  9. Notice that the VBE doesn’t delete the declaration and End statements for the Sub procedure that works with the default event (step #4). If you want to keep a clean module, you can delete them.

    Extra macro declaration to delete

If you’re working in the UserForm window, you can use an alternative process. In this case, you can get the VBE to enter the declaration statement for the event-handler procedure in the following 2 simple steps:

  1. Either (i) double-click on the object you want to work with, or (ii) right-click on the object and select “View Code”.

    In the screenshot below, I select a CommandButton.

    Right-click control and View Code

  2. The VBE takes you to the UserForm’s Code window. Additionally, the VBE enters the declaration and End statements for the Sub procedure that handles the default event of the object, and places the cursor between these 2 statements.

    For example, in the screenshot below, the VBE adds the opening and closing statements for a macro triggered by the Click event of the CommandButton (Private Sub CommandButton1_Click())

    Private Sub CommandButton1_Click

    If you want to work with the default event of the object, you can start coding your Sub procedure.

    If you want to work with another event, repeat steps #6 through #9 from the process I describe above, as follows:

    1. Click on the Procedure drop-down list.

      Procedure drop-down list in VBE

    2. Select the event you want to work with.

      In the screenshot below, I select the double click (Dblclick) event.

      Procedure drop-down list and DblClick

    3. Start coding your Sub procedure, using the declaration and End statements that the VBE enters as a basis.

      Private Sub CommandButton1_DblClick

    4. If necessary, delete the declaration and End statements for the default event.

      Unused event-handler declaration

How To Refer To UserForm Controls Within Your Code

UserForms and UserForm controls are objects. You generally refer to them by using their Name property. The Name property is the first in an alphabetically-organized Properties Window.

UserForm Name property

You can see how to, and why, modify the Name property of UserForm controls in a previous section.

You can see the UserForm as the parent object of the controls within it. Therefore, the basic control reference structure is as follows:

UserForm.Control

“UserForm” is the UserForm object. “Control” is the control you’re referring to.

However, you usually refer to controls within event-handler procedures that are stored in the UserForm’s Code module. Therefore, you can simplify the reference by omitting a reference to the UserForm. In this case, you can refer to a control as follows:

Control

An additional alternative is to use the Me keyword to refer to the UserForm. In this case, the reference structure is as follows:

Me.Control

How To Display Or Load A UserForm

You can display a UserForm in the following 2 easy steps:

  1. Go to the appropriate module.
  2. Within the appropriate procedure, enter a statement that uses the Show method of the UserForm object. The basic structure of this statement is as follows:

    UserForm.Show

    “UserForm” is an optional UserForm object. If you omit this qualifier, VBA assumes you’re referring to the UserForm that is associated with the active UserForm module.

    The Show method has 1 parameter: modal. This allows you to specify whether the UserForm is modal or modeless. I don’t cover this topic in this UserForms Tutorial.

When choosing the procedure in which to include the Show method, consider how and when you want the user to access the UserForm. You can, for example:

  1. Create a procedure whose sole purpose is to display the UserForm.
  2. Assign that procedure to a button or keyboard shortcut.

You can also include the Show method in event-handler procedures. In such cases, the UserForm is displayed when the relevant event occurs.

You can load a UserForm, without displaying it, by working with the Load statement. In this case, the basic statement syntax is as follows:

Load UserForm

“UserForm” is a UserForm object.

When a UserForm is loaded, it exists in memory but isn’t visible. Therefore, you can programmatically work with the UserForm. The user, however, can’t interact with it.

Once you want to display a previously-loaded UserForm, you can use the Show method of the UserForm object.

You usually load a UserForm, without displaying it immediately, when the UserForm is complex and takes too long to load into memory. Once the UserForm is loaded in memory, you can quickly display it.

In certain cases, VBA loads the UserForm automatically without you having to use the Load statement. This is the case when you use the Show method of the UserForm object (above).

Where To Store The Macro That Displays A UserForm

You use the Show method within the procedure where you want to display the UserForm. This procedure is usually stored within a regular VBA module. You don’t store the macro that displays the UserForm in the UserForm Code window itself.

To understand why this is the case, it may help if you consider the following 3 separate steps:

  1. First, you need to get Excel to display the UserForm.
  2. Once the UserForm is shown, the user can work with it.
  3. Depending on what the user does with the UserForm, something happens.

The code that determines what happens depending on how the user interacts with the UserForm (step #3) is stored within the UserForm. If the UserForm is never displayed, the user doesn’t interact with the UserForm and this code is never executed.

Since the code within the UserForm is never executed if the UserForm isn’t displayed, you can’t store the code that determines when the UserForm is displayed in the UserForm Code module. If you store the code that displays a UserForm within the UserForm itself, the UserForm is never displayed.

How To Display A UserForm From The VBE

You can display a UserForm while working in the VBE by using the Run Macro (Sub/UserForm) command. You can execute the Run Macro (Sub/UserForm) command in any of the following 3 ways:

  1. Clicking on the Rub Macro button in the VBE toolbar.
  2. Going to Run > Run Macro.
  3. Using the “F5” keyboard shortcut.

Run and Run Macro and Run Macro command

When you execute the Run Sub/UserForm command, the Initialize event of the UserForm occurs. This option is useful for testing or preparing a UserForm you’re working on.

As an alternative to the Run Sub/UserForm command, you can use the Show method of the UserForm object in a statement typed in the Immediate Window. The basic structure of such a statement is:

UserForm.Show

“UserForm” is a UserForm object.

UserForm.Show

How Is The Control Flow When Excel Displays A UserForm

At a basic level, once the Show method of the UserForm object is called, Excel goes through the following 6-step process:

  1. Displays the UserForm.
  2. Waits for the user to work with the UserForm.
  3. The interaction of the user with the UserForm usually triggers an event associated to 1 of the controls within the UserForm. Therefore, the applicable event-handler procedure is executed.
  4. Once an event-handler procedure runs, control returns to the UserForm.
  5. Eventually, the UserForm is closed or dismissed by the user.
  6. Once the UserForm is closed, Excel continues execution of the procedure that contains the Show method of the UserForm object. This is the Sub procedure responsible for displaying the UserForm (step #1 above).

    In practice, however, the VBA statement that displays the UserForm is at (or near) the end of a procedure. This is because you usually store the code that is executed after the user works with the UserForm in the UserForm Code module. The code within the UserForm Code module is executed in earlier steps of this process (steps #2 to #4 above).

    You can read more about the UserForm Code module in a previous section of this UserForm Tutorial.

How To Close Or Hide A UserForm

There are few different ways in which a UserForm can be closed or hidden.

The first way in which a UserForm can be closed is by clicking on its Close button on the top right corner. This generally applies to all UserForms, regardless of the VBA code you use.

UserForm and X button

You can, however, monitor whether a user clicks on the Close button by using events. Clicking on the Close button triggers the following 2 events:

  1. QueryClose: Occurs before the UserForm is closed.
  2. Terminate: Occurs after the UserForm is unloaded and when the UserForm is removed from memory.

Usually, when you’re creating a UserForm, you create an event-handler procedure that is triggered by the Click event of a CommandButton. This event-handler procedure normally includes 1 of the following VBA constructs:

  1. The Unload statement, which unloads the UserForm from memory. The basic statement structure for the Unload statement is as follows:

    Unload UserForm

    “UserForm” is a UserForm object.

  2. The UserForm.Hide method, which makes the UserForm invisible. The basic statement syntax for the UserForm.Hide method is as follows:

    UserForm.Hide

    “UserForm” is a UserForm object.

In both cases, if the procedure containing this statement is stored within the UserForm Code module, you can use the Me keyword. In such a case, you can always use the same statement regardless of the Name property of the UserForm. Additionally, you can replace the statements above with the following:

Unload Me

Me.Hide

You generally use the Unload statement only after all the UserForm instructions and statements have been carried out. This includes retrieving the input data from the UserForm and carrying out any necessary actions. If you fail to do this, the UserForm has no real effect, other than displaying the UserForm itself.

I don’t cover the topic of retrieving input from a UserForm in detail within this blog post. But you can see some code examples further below.

This topic is important because, once a UserForm is unloaded, the changes made to the UserForm’s controls and their properties are reset. This results, as explained in Excel 2016 Power Programming with VBA, your code not being “able to access the user’s choices after the UserForm is unloaded.”

There may be cases where you need to use the input from a UserForm after the UserForm is unloaded. You can usually store that data using a public-scope variable. Other possible solutions suggested by VBA experts Dick Kusleika and Mike Alexander in Excel 2016 Power Programming with VBA include writing the value to a worksheet cell or the Windows registry.

The UserForm.Hide method doesn’t unload the UserForm from memory. It simply hides the UserForm. Therefore, you can still access and work with the user’s choices and the UserForm controls.

In fact, if you use the UserForm.Hide method on an unloaded UserForm, VBA loads the UserForm and keeps it hidden.

As explained in the Excel 24-Hour VBA Trainer:

The method you choose depends on why you don’t want the UserForm to be seen. Most of the time, you’ll want the form cleared from memory, but sometimes, information that was entered into the form needs to be referred to the next time you show the form while the workbook has remained open.

Example: Create A Simple UserForm For Data Entry

This UserForm Tutorial is accompanied by an Excel workbook example. If you want to follow the steps I describe below, get immediate free access to this workbook by clicking the button below.

Get immediate free access to the Excel workbook example

The purpose of the example UserForm is to serve as a data entry mechanism for a workbook table recording certain sales data. The entries are as follows:

  • Item.
  • Units Sold.

The worksheet where these entries are recorded has 2 single columns. These columns match with the entries above.

Data entry table

These entries are the part of the basis for several tables that I use in other Tutorials, such as this one about Pivot Tables or this one about Power Query.

The example UserForm that you create below works with the following UserForm controls:

  • 1 Label.
  • 1 TextBox.
  • 1 SpinButton.
  • 1 Frame.
  • 5 OptionButtons.
  • 2 CommandButtons.

In the following sections, you follow the 6-step process described at the beginning of this Tutorial to create a UserForm:

  1. Insert a UserForm.
  2. Add controls to the UserForm.
  3. Move or resize the UserForm controls.
  4. Customize the UserForm or its controls.
  5. Assign VBA code to the UserForm.
  6. Display or load the UserForm.
  7. Close or hide the UserForm.

The purpose of this section is to show you, step-by-step, the practical process you can follow to create a UserForm. The logic and theory behind each of these steps is thoroughly described in the appropriate section above. Please refer to those sections for more information and details.

The UserForm example you create is very simple. My purpose with this blog post is to get you started creating UserForms. Therefore, I don’t dive into certain features or VBA constructs that you can use and add to improve the UserForm and make it more sophisticated or complex.

Step #1: Insert A UserForm

Insert the UserForm by following these 3 easy steps:

  1. Use the “Alt + F11” keyboard shortcut to go to the VBE.
  2. Go to the Project Explorer and right-click on the Project (workbook) you’re working on. In this example, select “VBAProject(Create Excel UserForms For Data Entry In 6 Easy Steps.xlsm)”.
  3. Go to Insert > UserForm.

    Right-click workbook and Insert and UserForm

The Visual Basic Editor creates the following blank UserForm.

Blank UserForm in VBE

Step #2: Add Controls To The UserForm

The purpose of the example UserForm example is to serve for data entry. There are only 2 required entries:

  1. Item.
  2. Units Sold.

To achieve this, use the following controls for the UserForm:

  • 1 SpinButton, to specify the number of units sold.
  • 1 TextBox, to display the number of units sold specified by clicking on the SpinButton.
  • 1 Label for the TextBox.
  • 5 OptionButtons, to choose the appropriate item. In this example, you use OptionButtons because you want to ensure that the user can select only 1 item (not several).
  • 1 Frame, for the OptionButtons.
  • 2 CommandButtons: A Record Entry and a Close Form button.

Add the SpinButton, TextBox, Label and Frame controls following the same 2-step process:

  1. Select the control in the Toolbox.
  2. Click on the UserForm, in the location where you want to add the control.

In the case of the CommandButtons and OptionButtons, use the following 3-step process:

  1. Double-click on the control within the Toolbox.
  2. Click on the UserForm several times, once for each time you add the control (2 for the CommandButtons, 5 for the OptionButtons).
  3. Click on the Select Objects command in the Toolbox to restore the mouse pointer to Selection mode.

Due to the amount of controls you include in the UserForm, start by resizing the UserForm itself. Your purpose is to make the UserForm taller. You do this by clicking and dragging on the UserForm’s lower center sizing handle.

UserForm and Lower center resizing handle

Once the UserForm is big enough to fit all the controls you want to add, and due to the layout choice, add the controls in the following order:

  1. Frame.
  2. OptionButtons.
  3. Label.
  4. TextBox.
  5. SpinButton.
  6. CommandButtons.

The following GIF shows the process I describe above:

Add controls to UserForm

In this step, don’t worry too much in getting the precise location right. You organize the controls with more detail in the next step.

Step #3: Move Or Resize The UserForm Controls

Use the grid and several commands in the Format menu to arrange the controls within the UserForm. The exact commands you use vary depending on the exact situation you’re in.

For this example, do the following:

  1. Arrange the vertical spacing between the different OptionButtons and align them to the left, as follows:
    1. Select all the OptionButtons.
    2. Go to Format > Vertical Spacing > Remove.
    3. Go to Format > Vertical Spacing > Increase.
    4. Change the reference control by holding the Ctrl key while clicking on an OptionButton that has the appropriate alignment.
    5. Go to Format > Align > Lefts.
  2. Reduce the height of the Frame used to group the OptionButtons. Do this by clicking on and dragging on its lower center sizing handle.
  3. Move the Label, TextBox, SpinButton and CommandButtons up, so that they’re closer to the lower edge of the Frame. Do this by selecting all the controls and dragging them with the mouse.
  4. Align all controls, except the SpinButton and the CommandButton on the right side of the UserForm, to the left. Do this as follows:
    1. Select all controls, excluding the SpinButton and the right-hand CommandButton.
    2. Go to Format > Align > Lefts.
  5. Make the SpinButton the same height as the TextBox and align both controls, as follows:
    1. Select the SpinButton and the TextBox.
    2. Go to Format > Make Same Size > Height.
    3. Go to Format > Align > Rights.
    4. Go to Format > Align > Tops.
  6. Arrange the vertical spacing between the TextBox and the left-hand CommandButton, as follows:
    1. Select the left-hand CommandButton and the TextBox.
    2. Go to Format > Vertical Spacing > Remove.
    3. Go to Format > Vertical Spacing > Increase.
  7. Align the CommandButtons, as follows:
    1. Select the CommandButtons.
    2. Go to Format > Align > Tops.
    3. Go to Format > Horizontal Spacing > Remove.
    4. Go to Format > Horizontal Spacing > Increase.
  8. Decrease the height of the UserForm by using its lower center sizing handle.
  9. Decrease the width of both the Frame and the UserForm. In both cases, click and drag on their respective right center sizing handles.

The following GIF shows the 9-step process I describe above:

Organize controls in UserForm

Step #4: Customize The UserForm And Its Controls

Customize the following 2 properties of all UserForm and UserForm controls that contain them:

  1. Name: The name of the UserForm or control.
  2. Caption: Caption text that is displayed (i) within or next to a control, or (ii) in the UserForm title bar.

The only exceptions are the TextBox and SpinButton. The TextBox and SpinButton objects don’t have a Caption property.

In addition to the above, make the following specific property modifications:

  1. Set the Default property of the Record Entry button to True. The Default property allows you to specify whether a CommandButton is the default button in the UserForm.
  2. Set the Cancel property of the Close Form button to True. You can use the Cancel property to specify that a CommandButton is the Cancel button. If you do this, the user can use the Escape key as a shortcut for the Close Form button.
  3. Set the Enabled property of the TextBox to False. You can use the Enabled property to indicate whether the TextBox is enabled and respond to the user’s actions (True) or disabled (False).
  4. Set the Locked property of the TextBox to True. The Locked property allows you to specify if the user can edit the entry or data within the TextBox. By locking the TextBox, you ensure that the user can’t edit, add or delete data in the TextBox.

Follow the same 3-step process for all objects whose properties are modified:

  1. Select the object to modify.
  2. Go to the Properties Window and select the appropriate property.
  3. Double-click on the current property setting, and (when required) replace it with a new one. With some of the properties used in this example Default, Cancel, Enabled and Locked), double-clicking allows you to cycle through the available values (True and False).

The following table shows the new Name and Caption properties for each of the objects. I use “n.a.” to indicate the cases where a property isn’t a member of the object.

Original Object Name Name Property Caption Property
UserForm1 userFormSalesEntry Enter sales data
Label1 labelUnits No. of units sold
TextBox1 textBoxUnits n.a.
SpinButton1 spinButtonUnits n.a.
Frame1 frameItem Item
OptionButton1 optionButtonSurfaceStudio Surface Studio
OptionButton2 optionButtonSurfaceBook Surface Book
OptionButton3 optionButtonSurfacePro4 Surface Pro 4
OptionButton4 optionButtonXboxOneS Xbox One S
OptionButton5 optionButtonXboxOne Xbox One
CommandButton1 commandButtonRecordEntry Record Entry
CommandButton2 commandButtonCloseForm Close Form

Strictly speaking, you don’t need to specify the Name property of all the objects above. This is because you don’t refer to most of them (for example, the Label and Frame) within the VBA code you create in the following steps. However, as I explain above, you generally want to use meaningful and descriptive names for the objects you refer to within the code.

The following GIF shows the whole process to change the properties above:

Specify control properties

Step #5: Assign VBA Code To The UserForm

My focus in this UserForms Tutorial are UserForms, not VBA code. My purpose is to show you how you can use some of the VBA constructs I explain in the first section of this blog post, such as the Unload statement.

Therefore, the Sub procedure examples below are very simple. You can use more sophisticated macros and find several Tutorials that focus on VBA code in the Archives.

In this step, you create the following 3 macros:

  1. A macro that prepares the UserForm for use by setting the default states of the TextBox, SpinButton and OptionButtons in the UserForm.
  2. A macro that records entries.
  3. A macro that connects the TextBox to the SpinButton, so that changes to the SpinButton are reflected in the TextBox.

I explain the VBA code used to display and close the UserForm in the following steps (#6 and #7).

The 8-step process you can follow to enter the VBA code for the UserForm is as follows:

  1. Double-click the Record Entry CommandButton.

    Enter sales data dialog box and Record Entry

    Because of this, the VBE does the following:

    • Takes you to the Code window.
    • Enters the declaration and End statements for a Sub procedure triggered by the Click event of the CommandButton object (Private Sub commandButtonRecordEntry_Click()). The Click event occurs when the user clicks on the CommandButton.

      Private Sub commandButtonRecordEntry_Click

  2. Enter the VBA code for the Sub procedure triggered when the user clicks on the Record Entry CommandButton. This is the main Sub procedure and carries out most of the work you require.
  3. Click on the Object drop-down list at the top left side of the UserForm Code window, and select the SpinButton control (spinButtonUnits).

    Object drop-down list and SpinButton

    The VBE enters the declaration and End statements for a Sub procedure triggered by the Change event of the spinButtonUnits object (Private Sub spinButtonUnits_Change()). The Change event occurs when the Value property of the SpinButton changes. The Value property, in turn, changes when the user clicks any of the arrows of the SpinButton.

    Private Sub SpinButton_Change

  4. Enter the VBA code for the Sub procedure triggered when the user clicks on the arrows of spinButtonUnits.
  5. Click on the Object drop-down list, and select the UserForm object (UserForm).

    Object drop-down list and UserForm

    Because of this, the VBE enters the declaration and End statements for a Sub procedure triggered by the Click event of the UserForm.

    Private Sub UserForm_Click

  6. Click on the Procedure drop-down list at the top right side of the UserForm Code Window, and select the Initialize event.

    Procedure drop-down list and Initialize

    The VBE enters the opening and closing statements of a Sub procedure triggered by the Initialize event of the UserForm (Private Sub UserForm_Initialize()). The Initialize event happens when the UserForm is loaded, but prior to it being displayed. Therefore, you usually rely on Initialize to specify default values or fill controls with data.

    Private Sub UserForm_Initialize

  7. Delete the opening and closing statements entered by the VBE in step #5 above (Private Sub UserForm_Click()).

    Extra event-handler procedure to delete

  8. Enter the VBE code for the macro triggered when the UserForm is initialized.

Let’s look at the VBA code for the 3 procedures you create in this step:

Sub Procedure #1: Private Sub UserForm_Initialize()

The following is the VBA code for the macro executed when the UserForm is initialized:

Code for TextBox.Text, SpinButton.Value, OptionButton.Value

This macro sets the default values and selections for several controls within the UserForm, as follows:

  • Value of TextBox: 0.
  • Value of SpinButton: 0.
  • Selected OptionButton: Surface Studio.

You can also manipulate these properties through the Properties Window (step #4 above).

One of the main reasons I prefer to set these default property values through VBA code is that this allows me to reuse the code within this Sub procedure to reset the UserForm and prepare it for a new entry. In fact, the last statement in Sub procedure #2 below calls the UserForm_Initialize macro for these purposes.

Let’s look at each line of code within this macro:

Lines #1 And #5: With Me | End With

Opening and closing statements of a With… End With block.

The statements within the block (lines #2 to #4) work with the object specified in the opening line of the block (Me). You use the Me keyword to refer to the UserForm itself.

Line #2: .textBoxUnits.Text = 0

Sets the default value of the TextBox to 0. This default number of units (0) is recorded when the user fails to specify one through the SpinButton control.

You achieve this by setting the Text property of the TextBox (.textBoxUnits.Text) to 0.

Line #3: .spinButtonUnits.Value = 0

Sets the default value of the SpinButton to 0. This value matches the default value of the TextBox (line #2 above).

You do this by setting the Value property of the SpinButton to 0. The Value property of a SpinButton is an integer.

Line #4: .optionButtonSurfaceStudio.Value = True

Selects (by default) the OptionButton that corresponds to the Surface Studio.

You achieve this by setting the Value property of the first OptionButton (Surface Studio) to True. The Value property allows you to specify whether the OptionButton is selected (True).

Private Sub commandButtonRecordEntry_Click()

The following is the VBA code within the Sub procedure executed when the user clicks the Record Entry button:

Macro code using Range.Find, Select Case, OptionButton.Value, TextBox.Value and other VBA constructs

This Sub procedure goes through the following process:

  1. Find the first empty row in the worksheet where the entered data is recorded.
  2. Record the user entries in that first empty row, as follows:
    1. The Item chosen with the OptionButtons of the UserForm is recorded in column A.
    2. The number of units displayed in the TextBox of the UserForm is recorded in column B.
  3. Prepare the UserForm for a new entry by:
    1. Resetting the values of the TextBox and SpinButton.
    2. Selecting the default OptionButton (for Surface Studio).

The macro doesn’t carry any data validation checks, nor handles any possible errors. For example, it doesn’t check whether the user has entered the number of units using the SpinButton. In this example, those checks are mostly handled by the SpinButton and the properties of the TextBox you modify in step #4 above, as follows:

  • The user can’t enter data directly in the TextBox. This is a consequence of the values you set for the Enabled (False) and Locked (True) properties of the TextBox in step #4 above.
  • The number of units displayed on the TextBox is dependent on the SpinButton. In other words, the user specifies the number of units through the SpinButton. The TextBox simply displays the current number of units.

    You achieve this through an event-handler procedure triggered by the Change event of the SpinButton object. You can find an example of such code below (Sub procedure #3).

This Sub procedure doesn’t close the UserForm. Therefore, the user can make several entries at any time without having to continually open the dialog box. The user can, however, close the dialog box at any time by clicking on the Close or Close Form buttons. See step #7 below to see how to close the dialog box with the Close Form button.

Let’s go through each line of code to understand how the macro works:

Lines #1 And #2: Dim myWorksheet As Worksheet |Dim myFirstBlankRow As Long

Use the Dim keyword to declare 2 variables:

  1. myWorksheet: An object variable. Represents the worksheet where the data is recorded.
  2. myFirstBlankRow: A variable of the Long data type. Represents the number of the first blank row in the table where the data is recorded.
Line #3: Set myWorksheet = Worksheets(“Excel UserForm data entry”)

Uses the Set keyword to assign a worksheet (Excel UserForm data entry) to an object variable (myWorksheet).

Lines #4 And #21: With myWorksheet | End With

Opening and closing statements of a With… End With block. The statements within the block (lines #5 to #20) work with the object specified in the opening line of the block (myWorksheet).

Lines #5: myFirstBlankRow = .Cells.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row + 1

Finds the first empty row in myWorksheet and assigns its number to the myFirstBlankRow variable.

The process followed to find the first empty row in the worksheet is as follows:

  1. The number of the last cell with data in the worksheet is found (.Cells.Find(What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row).
  2. A value of 1 is added. This addition returns the number of the row below the last cell with data or, in other words, the first empty row in the worksheet.

Let’s analyze the portion of the statement that finds the last row in the worksheet. I explain several different ways to find the last row in a worksheet in this VBA Tutorial.

  1. The Worksheet.Cells property (.Cells) returns all the cells within myWorksheet.
  2. The Range.Find method (Cells.Find) is used to search for the last cell with data within myWorksheet. The parameters of the Range.Find method, which are within parentheses, are set as follows:
    1. What: “*”. The data you’re searching for. The asterisk (*) acts as wildcard. Therefore, the Find method searches for any character sequence.
    2. LookIn: xlFormulas. The type of data you’re searching in. xlFormulas results in VBA searching (looking) in the cell formulas.
    3. LookAt: xlPart. Specifies whether the Find method matches the cell contents in their entirety, or just a part of them. xlPart results in Excel doing a partial match.
    4. SearchOrder: xlByRows. Specifies whether the search is carried out by rows or by columns. Since you’re looking for the last row, you set this to xlByRows.
    5. SearchDirection: xlPrevious. The direction (next or previous) in which the search is carried. In this case, you set the argument so that Excel searches for the previous (xlPrevious) match.

Once the last row in the worksheet is identified, 1 is added (+ 1). The resulting value is assigned to the myFirstBlankRow variable (myFirstBlankRow =).

Lines #6 And #19: With .Cells(myFirstBlankRow, 1) | End With

Opening and closing statements of a With… End With block. The statements within the block (lines #7 to #18) work with the object specified in the opening line of the block (.Cells(myFirstBlankRow, 1)).

Let’s analyze the object to which statements refer to:

  • The Cells property (.Cells) works with the object specified in the opening statement of the outer With… End With block (line #4 above). That object is myWorksheet.
  • The Cells property returns a single cell. That’s the cell located on the first empty row (myFirstBlankRow) and the first column (1 or A) of the worksheet. This cell is where the next data entry for Item is recorded.

    First empty cell in column A

Lines #7 And #18: Select Case True | End Select

Opening and closing of a Select Case statement.

Executes one of the groups of statements within this block of code (lines #8 to #17) based on the value taken by an expression. The group of statements that’s executed is determined by finding which expression matches the test expression.

The test expression is set in the opening line of code (#7) of the block. In this case, a Boolean value: True (Select Case True).

Lines #8 Through #17: Case optionButtonSurfaceStudio.Value | .Value = “Surface Studio” | Case optionButtonSurfaceBook.Value | .Value = “Surface Book” | Case optionButtonSurfacePro4.Value | .Value = “Surface Pro 4” | Case optionButtonXboxOneS.Value | .Value = “Xbox One S” | Case optionButtonXboxOne.Value | .Value = “Xbox One”

Line #8, #10, #12, #14 and#16 are the expressions against which VBA seeks to match the test expression (True) from line #7 above. The statement that VBA executes is the one following the expression that returns True and, therefore, matches the test expression.

The following table shows the tested expressions along with the statement that’s executed when that expression returns True:

Rows # Expression Statement that’s executed if Expression = True
8 and 9 optionButtonSurfaceStudio.Value .Value = “Surface Studio”
10 and 11 optionButtonSurfaceBook.Value .Value = “Surface Book”
12 and 13 optionButtonSurfacePro4.Value .Value = “Surface Pro 4”
14 and 15 optionButtonXboxOneS.Value .Value = “Xbox One S”
16 and 17 optionButtonXboxOne.Value .Value = “Xbox One”

Notice the following:

  1. The structure of all the groups of statements above is identical.
  2. First, you have the expression that VBA seeks to match with the test expression (True).
    1. The OptionButton.Value property returns True if the OptionButton is selected.
    2. The OptionButtons used in this example are grouped. Therefore, when the user selects 1 option, the other options are automatically de-selected. In other words, only 1 OptionButton can be selected.
    3. Because of #1 and #2 above, the expression that matches the test expression is that which corresponds to the OptionButton selected by the user.
  3. Second, you have the statement that VBA executes when the corresponding expression is True.
    1. The Value property (.Value) works with the object specified in the opening statement of the With… End With block (line #6). That object is the cell where the next entry for Item goes.
    2. The executed statement sets the Value property of the relevant cell to be equal to a string. This string is the name of one of the Items.

Overall, the consequence of the above structure is that the data recorded in the Excel worksheet depends on the OptionButton the user chooses, as follows:

If the user chooses The data entry is
Surface Studio Surface Studio
Surface Book Surface Book
Surface Pro 4 Surface Pro 4
Xbox One S Xbox One S
Xbox One Xbox One
Line #20: .Cells(myFirstBlankRow, 2).Value = Me.textBoxUnits.Value

Records the number of units within the No. of units sold TextBox in the appropriate worksheet cell.

Let’s see how this works:

  1. The statements sets the Value property of a cell (.Cells(myFirstBlankRow, 2).Value =) to be equal to the Value property of the UserForm TextBox (Me.textBoxUnits.Value). The Value property of the TextBox is determined by the SpinButton. This part of the process is controlled by the Sub procedure #3 I explain below.
  2. The first part of the statement (.Cells(myFirstBlankRow, 2)) works as follows:
    1. The Cells property (.Cells) works with the object specified in the opening statement of the With… End With block (line #4). That object is represented by myWorksheet.
    2. The Cells property returns a single cell. This cell is located on the first empty row (myFirstBlankRow) and the second column (2 or B) of the worksheet. That’s the cell where the next data entry for Units Sold is recorded.

      Cell for next entry

Line #22: UserForm_Initialize

Calls the UserForm_Initialize Sub procedure. I explain this event-handler procedure in more detail above (Sub procedure #1).

The UserForm_Initialize macro sets the default values and controls of certain UserForm controls, as follows:

  • TextBox: 0.
  • SpinButton: 0.
  • OptionButton selection: Surface Studio.

In other words, by calling the UserForm_Initialize Sub procedure, you reset the values and selections within the UserForm to their defaults. This ensures that the UserForm is ready for a new entry.

Sub Procedure #3: Private Sub spinButtonUnits_Change()

The following is the VBA code within the Sub procedure executed when the user clicks on any of the arrows of the SpinButton control:

TextBox.Value = SpinButton.Value

This macro consists of a single VBA statement:

textBoxUnits.Value = Me. spinButtonUnits.Value

This statement sets the Value property of the TextBox object (textBoxUnits.Value) to be equal to the Value property of the SpinButton object (Me.spinButtonUnits.Value). In other words, it:

  • Connects the TextBox to the SpinButton.
  • Ensures that the value displayed in the TextBox is determined by the SpinButton.

Step #6: Display The UserForm

For this example, get Excel to display the UserForm in the following 3 simple steps:

  1. Go to a module different from the UserForm’s code module.
  2. Create a Sub procedure that calls the Show method of the UserForm object.
  3. Assign a keyboard shortcut to the displayUserForm macro.

Let’s go through each of these steps:

Step #1: Go To A Module

In this example, store the macro that displays the UserForm in a standard module (Module1).

If necessary, insert a new module by, for example, right-clicking on the workbook within the Project Explorer and going to Insert > Module.

Right-click and Insert and Module

Step #2: Create A Sub Procedure That Calls The Show Method Of The UserForm Object

Create the following macro (displayUserForm):

UserForm.Show

displayUserForm consists of the following single statement:

userFormSalesEntry.Show

When executed, this macro displays the userFormSalesEntry you created in the previous 5 steps.

Step #3: Assign A Keyboard Shortcut To The displayUserForm Macro

For this example, execute the displayUserForm Sub procedure with a keyboard shortcut. Make this assignment in the following 4 easy steps:

  1. Open the Macro dialog box by, for example, using the “Alt + F8” keyboard shortcut.
  2. Within the Macro dialog box, select the appropriate macro (displayUserForm) and click the Options button.

    Macro dialog box and Macro name and Options

  3. Within the Macro Options dialog box displayed by Excel, assign a keyboard shortcut and click the OK button.

    In this example, assign the keyboard shortcut “Ctrl + Shift + A”.

    Macro Options dialog and Ctrl + Shift + A and OK

  4. Close the Macro dialog box.

    Macro dialog and X

Step #7: Close The UserForm

A user can close the dialog box example by clicking on the Close Form button. You can enter the code to close the UserForm when the user clicks this button in the following 4 easy steps:

  1. Go to the VBE by, for example, using the “Alt + F11” keyboard shortcut.
  2. Double-click on the appropriate UserForm module (userFormSalesEntry).

    UserForm to double-click in Project Explorer

  3. Double-click on the button you want to use to close the UserForm (Close Form).

    Enter sales data and Close Form

    Because of this, the VBE does the following:

    • Takes you to the UserForm’s Code window.
    • Enters the declaration and End statements for a Sub procedure triggered by the Click event of the commandButtonCloseForm object (Private Sub commandButtonCloseForm_Click()).

      Private Sub CommandButton_Click

  4. Enter the VBA code for the Sub procedure triggered when the user clicks the Close Form button. In this example, this procedure includes a statement with the Unload statement.

The following is the code within the Sub procedure executed when the user clicks the Close Form button:

Unload Me

This Sub procedure has the following single statement:

Unload Me

The Unload statement unloads the UserForm from memory. This results in the dialog box being dismissed.

UserForm For Data Entry In Action

You can enter data with the UserForm example in the following 5 simple steps:

  1. Use the “Ctrl + Shift + A” keyboard shortcut.
  2. Excel displays the UserForm.

    Enter sales data UserForm

  3. To make an entry:
    1. Enter the number of units sold by using the SpinButton.
    2. Choose the appropriate Item.
    3. Click on the Record Entry button.

      Item, No. of units sold, Record Entry button in UserForm

  4. Repeat step #3 as many times as required, depending on the number of entries you want to make.
  5. To close the UserForm, press the Close or Close Form button.

    Enter sales data and X, Close Form

The GIF below shows the UserForm in action. Notice how:

  • Every time I click the Record Entry button, the entry is recorded in the table.
  • When I click the Close Form button, the dialog box is closed.

Example to enter data with UserForm

Conclusion

After reading this UserForms Tutorial, you have the knowledge and resources to start creating UserForms in Excel now. The following are some of the topics you learned about:

  • What is a UserForm, and why are they useful.
  • The simple 6-step process you can use to create a UserForm for data entry.
  • How to insert and customize UserForms.
  • What are UserForm controls, and how you work with them. This includes, among others, how to add, select, move, resize, customize and remove controls.
  • How to create the macros that power your UserForms. This includes the VBA code you use to both: (i) display, load, close and hide UserForms, and (ii) respond to the user’s actions within the UserForm.

In the second section of this UserForms Tutorial, you saw a practical example. In this example, you followed the easy 6-step process to create a simple UserForm for data entry. Remember that this blog post is accompanied by an Excel workbook example containing this UserForm example. You can get immediate free access to this workbook by clicking the button below.

Get immediate free access to the Excel workbook example

In practice, you’re likely to work with more complex UserForms that (i) gather more data, (ii) use additional controls, and (iii) work with more complex VBA code. In most cases, the basic principles and constructs you’ve learned about by reading this UserForms Tutorial continue to apply.

Books Referenced In This UserForms Tutorial

  • Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
  • Goldmeier, Jordan (2014). Advanced Excel Essentials. New York City, NY: Apress.
  • Mansfield, Richard (2016). Mastering VBA for Microsoft Office 2016. Indianapolis, IN: John Wiley & Sons Inc.
  • Urtis, Tom (2015). Excel VBA 24-Hour Trainer. Indianapolis, IN: John Wiley & Sons Inc.

Понравилась статья? Поделить с друзьями:
  • Excel vba index cell
  • Excel vba if сравнение текста
  • Excel vba if несколько действий
  • Excel vba if два условия
  • Excel vba if больше или равно