Excel vba ввод данных через форму

Пример создания пользовательской формы в редакторе 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».


Visual Basic is an excellent language for automating repetitive tasks in Excel. Imagine taking your automation up a notch by creating highly functional user forms that also look tidy to the end-users.

User forms in VBA present you with a blank canvas; you can design and organize the forms to fit your needs at any given time.

In this guide, you will learn to create a student-based data entry form that captures relevant information in linked Excel sheets.

Creating a User Form With Excel VBA

Open a new Excel workbook and perform a few preliminary steps before you start creating your data-entry form.

Save your workbook with the desired name; don’t forget to change the file’s type to an Excel Macro-Enabled Workbook.

Add two sheets to this workbook, with the following names:

  1. Sheet1: Home
  2. Sheet2: Student Database

Excel sheet

Feel free to change these names as per your requirements.

In the Home sheet, add a button to control the user form macro. Go to the Developer tab and click on the Button option from the Insert drop-down list. Place the button anywhere on the sheet.

Excel workbook

Once you’ve placed the button, rename it. Right-click on it, and click on New to assign a new macro to show the form.

Enter the following code in the editor window:

  Sub Button1_Click()UserForm.ShowEnd Sub 

Once the Home and Student Database sheets are ready, it’s time to design the user form. Navigate to the Developer tab, and click on Visual Basic to open the Editor. Alternatively, you can press ALT+F11 to open the editor window.

Click on the Insert tab and select UserForm.

A blank user form is ready for use; an accompanying toolbox opens along with the form, which has all the essential tools to design the layout.

Excel VBA editor

From the toolbox, select the Frame option. Drag this to the user form and resize it.

In the (name) option, you can change the name of the frame. To showcase the name on the front-end, you can change the name in the Caption column.

Next, select the Label option from the toolbox and insert two labels within this frame. Rename the first one as Application Number and the second as Student ID.

Userform in Excel VBA

The same renaming logic applies; change the names via the Caption option within the Properties window. Make sure you select the respective label before changing its name.

Next, insert two text boxes next to the label boxes. These will be used to capture the user’s inputs. Change the names of two text boxes via the (Name) column within the Properties window. The names are as follows:

  • Textbox1: txtApplicationNo
  • Textbox2: txtStudentID

Designing the Student Details Frame

Insert a vertical frame and add 10 labels and 10 text boxes. Rename each of them in the following manner:

  • Label3: Name
  • Label4: Age
  • Label5: Address
  • Label6: Phone
  • Label7: City
  • Label8: Country
  • Label9: Date of Birth
  • Label10: Zip Code
  • Label11: Nationality
  • Label12: Gender

Insert corresponding text boxes next to these labels; insert two (or more) optionbutton boxes from the user form toolbox next to the gender label. Rename them Male and Female (along with Custom), respectively.

Designing the Course Details Frame

Add another vertical frame and insert six labels and six text boxes corresponding to each label. Rename the labels as follows:

  • Label13: Course Name
  • Label14: Course ID
  • Label15: Enrollment Start Date
  • Label16: Enrollment End Date
  • Label17: Course duration
  • Label18: Department

Designing the Payment Details Frame

Insert a new frame; add a new label and rename it «Do you wish to update the Payment details?» Insert two optionbuttons; rename them Yes and No.

Similarly, add a new frame containing two additional labels and two combo boxes. Rename the labels as follows:

  • Label19: Payment Received
  • Label20: Mode of Payment

Designing the Navigation Pane

In the final frame, add three buttons from the toolbox, which will contain code for the execution of the forms.

Rename the buttons in the following manner:

  • Button1: Save Details
  • Button2: Clear Form
  • Button3: Exit

Userform in Excel VBA

Writing the Automated Form Code: Save Details Button

Double-click on the Save Details button. In the ensuing module, insert the following code:

  Private Sub CommandButton2_Click()‘declare the variables used throughout the codesDim sht As Worksheet, sht1 As Worksheet, lastrow As Long'Add validations to check if character values are being entered in numeric fields.If VBA.IsNumeric(txtApplicationNo.Value) = False ThenMsgBox "Only numeric values are accepted in the Application Number", vbCriticalExit SubEnd IfIf VBA.IsNumeric(txtStudentID.Value) = False ThenMsgBox "Only numeric values are accepted in the Student ID", vbCriticalExit SubEnd IfIf VBA.IsNumeric(txtAge.Value) = False ThenMsgBox "Only numeric values are accepted in Age", vbCriticalExit SubEnd IfIf VBA.IsNumeric(txtPhone.Value) = False ThenMsgBox "Only numeric values are accepted in Phone Number", vbCriticalExit SubEnd IfIf VBA.IsNumeric(Me.txtCourseID.Value) = False ThenMsgBox "Only numeric values are accepted in Course ID", vbCriticalExit SubEnd If'link the text box fields with the underlying sheets to create a rolling databaseSet sht = ThisWorkbook.Sheets("Student Database")'calculate last populated row in both sheetslastrow = sht.Range("a" & Rows.Count).End(xlUp).Row + 1'paste the values of each textbox into their respective sheet cellsWith sht.Range("a" & lastrow).Value = txtApplicationNo.Value.Range("b" & lastrow).Value = txtStudentID.Value.Range("c" & lastrow).Value = txtName.Value.Range("d" & lastrow).Value = txtAge.Value.Range("e" & lastrow).Value = txtDOB.Value.Range("g" & lastrow).Value = txtAddress.Value.Range("h" & lastrow).Value = txtPhone.Value.Range("i" & lastrow).Value = txtCity.Value.Range("j" & lastrow).Value = txtCountry.Value.Range("k" & lastrow).Value = txtZip.Value.Range("l" & lastrow).Value = txtNationality.Value.Range("m" & lastrow).Value = txtCourse.Value.Range("n" & lastrow).Value = txtCourseID.Value.Range("o" & lastrow).Value = txtenrollmentstart.Value.Range("p" & lastrow).Value = txtenrollmentend.Value.Range("q" & lastrow).Value = txtcourseduration.Value.Range("r" & lastrow).Value = txtDept.ValueEnd Withsht.Activate'determine gender as per user's inputIf optMale.Value = True Then sht.Range("g" & lastrow).Value = "Male"If optFemale.Value = True Then sht.Range("g" & lastrow).Value = "Female"'Display a message box, in case the user selects the Yes radio buttonIf optYes.Value = True ThenMsgBox "Please select the payment details below"Else:Exit SubEnd IfEnd Sub 

If you’re not sure what parts or any of the code means, don’t worry. We’ll explain it thoroughly in the next section.

Automated Form Code Explained

The textboxes will contain a mix of text and numeric values, so it’s essential to restrict the user’s input. The Application Number, Student ID, Age, Phone, Course ID, and Course Duration should contain only numbers, while the rest will contain text.

Using an IF statement, the code triggers error pop-ups if the user enters a character or text value in any of the numeric fields.

Since the error validations are in place, you need to link the text boxes with the sheet cells.

The lastrow variables will calculate the last populated row, and store the values in them for dynamic use.

Finally, the values are pasted from the text boxes into the linked Excel sheet.

Clear Form and Exit Button Codes

In the clear button, you need to write the code to clear the existing values from the user form. This can be done in the following manner:

  With Me.txtApplicationNo.Value = "".txtStudentID.Value = ""..txtName.Value = "".txtAge.Value = "".txtAddress.Value = "".txtPhone.Value = "".txtCity.Value = "".txtCountry.Value = "".txtDOB.Value = "".txtZip.Value = "".txtNationality.Value = "".txtCourse.Value = "".txtCourseID.Value = "".txtenrollmentstart.Value = "".txtenrollmentend.Value = "".txtcourseduration.Value = "".txtDept.Value = "".cmbPaymentMode.Value = "".cmbPayment.Value = "".optFemale.Value = False.optMale.Value = False.optYes.Value = False.optNo.Value = FalseEnd With 

In the exit button, enter the following code to close the user form.

  Private Sub CommandButton5_Click()Unload MeEnd Sub 

As a last step, you need to input a few final pieces of code to create the drop-down values for the combo boxes (within the payment frames).

  Private Sub UserForm_Activate()With cmbPayment.Clear.AddItem "".AddItem "Yes".AddItem "No"End WithWith cmbPaymentMode.Clear.AddItem "".AddItem "Cash".AddItem "Card".AddItem "Check"End WithEnd Sub 

VBA Automation Makes Work Easier

VBA is a multi-faceted language that serves many purposes. User forms are only one aspect within VBA—there are many other uses like consolidating workbooks and worksheets, merging multiple Excel sheets, and other handy automation uses.

No matter the automation goal, VBA is up to the task. If you keep learning and getting practice in, there’s no aspect of your workflow you can’t improve.

Содержание

  1. Application.InputBox method (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Remarks
  6. Example
  7. Support and feedback
  8. Метод Application.InputBox (Excel)
  9. Синтаксис
  10. Параметры
  11. Возвращаемое значение
  12. Примечания
  13. Пример
  14. Поддержка и обратная связь
  15. VBA Excel. Первая форма (для начинающих)
  16. Создание пользовательской формы
  17. Добавление элементов управления
  18. Отображение формы на экране

Application.InputBox method (Excel)

Displays a dialog box for user input. Returns the information entered in the dialog box.

Syntax

expression.InputBox (Prompt, Title, Default, Left, Top, HelpFile, HelpContextID, Type)

expression A variable that represents an Application object.

Parameters

Name Required/Optional Data type Description
Prompt Required String The message to be displayed in the dialog box. This can be a string, a number, a date, or a Boolean value (Microsoft Excel automatically coerces the value to a String before it is displayed). Maximum length is 255 characters, otherwise there is no prompt, and Application’s method immediately returns Error 2015.
Title Optional Variant The title for the input box. If this argument is omitted, the default title is Input.
Default Optional Variant Specifies a value that will appear in the text box when the dialog box is initially displayed. If this argument is omitted, the text box is left empty. This value can be a Range object.
Left Optional Variant Specifies an x position for the dialog box in relation to the upper-left corner of the screen, in points.
Top Optional Variant Specifies a y position for the dialog box in relation to the upper-left corner of the screen, in points.
HelpFile Optional Variant The name of the Help file for this input box. If the HelpFile and HelpContextID arguments are present, a Help button will appear in the dialog box.
HelpContextID Optional Variant The context ID number of the Help topic in HelpFile.
Type Optional Variant Specifies the return data type. If this argument is omitted, the dialog box returns text.

Return value

The following table lists the values that can be passed in the Type argument. Can be one or a sum of the values. For example, for an input box that can accept both text and numbers, set Type to 1 + 2.

Value Description
0 A formula
1 A number
2 Text (a string)
4 A logical value (True or False)
8 A cell reference, as a Range object
16 An error value, such as #N/A
64 An array of values

Use InputBox to display a simple dialog box so that you can enter information to be used in a macro. The dialog box has an OK button and a Cancel button. If you select the OK button, InputBox returns the value entered in the dialog box. If you select the Cancel button, InputBox returns False.

If Type is 0, InputBox returns the formula in the form of text; for example, =2*PI()/360 . If there are any references in the formula, they are returned as A1-style references. (Use ConvertFormula to convert between reference styles.)

If Type is 8, InputBox returns a Range object. You must use the Set statement to assign the result to a Range object, as shown in the following example.

If you don’t use the Set statement, the variable is set to the value in the range, rather than the Range object itself.

If you use the InputBox method to ask the user for a formula, you must use the FormulaLocal property to assign the formula to a Range object. The input formula will be in the user’s language.

The InputBox method differs from the InputBox function in that it allows selective validation of the user’s input, and it can be used with Excel objects, error values, and formulas. Notice that Application.InputBox calls the InputBox method; InputBox with no object qualifier calls the InputBox function.

Example

This example prompts the user for a number.

This example prompts the user to select a cell on Sheet1. The example uses the Type argument to ensure that the return value is a valid cell reference (a Range object).

This example uses an InputBox for the user to select a range to pass to the user-defined function MyFunction, which multiplies three values in a range together and returns the result.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Метод Application.InputBox (Excel)

Отображает диалоговое окно для данных, вводимых пользователями. Возвращает данные, введенные в диалоговом окне.

Синтаксис

expression.InputBox (Prompt, Title, Default, Left, Top, HelpFile, HelpContextID, Type)

выражение: переменная, представляющая объект Application.

Параметры

Имя Обязательный или необязательный Тип данных Описание
Prompt Обязательно String Сообщение, которое отображается в диалоговом окне. Это может быть строка, число, дата или логическое значение (Microsoft Excel автоматически переводит значение в тип String перед отображением). Максимальная длина сообщения составляет 255 символов, в противном случае запрос не выводится, а метод приложения сразу же возвращает ошибку 2015.
Title Необязательный Variant Название поля для ввода. Если этот аргумент пропущен, используется заголовок по умолчанию «Ввод».
Default Optional Variant Задает значение, которое будет отображаться в текстовом поле при первоначальном отображении диалогового окна. Если этот аргумент пропущен, текстовое поле остается пустым. Это значение может представлять собой объект Range объекта.
Left Необязательный Variant Указывает положение по оси x для диалогового окна по отношению к левому верхнему углу экрана в пунктах.
Top Необязательный Variant Указывает положение по оси y для диалогового окна по отношению к левому верхнему углу экрана в пунктах.
HelpFile Optional Variant Имя файла справки для этого поля ввода. При наличии аргументов HelpFile и HelpContextID, кнопка «Справка» будет отображаться в диалоговом окне.
HelpContextID Optional Variant Номер идентификатора контекста раздела справки в HelpFile.
Type Необязательный Variant Задает тип возвращаемых данных. Если этот аргумент опущен, диалоговое окно возвращает текст.

Возвращаемое значение

Примечания

В таблице ниже перечислены значения, которые можно передать в аргументе Type. Это может быть одиночное значение или сумма значений. К примеру, для поля ввода, которое допускает ввод текста и чисел, задайте для аргумента Type значение 1 + 2.

Значение Описание
0 Формула
1 Число
2 Текст (строка)
4 Логическое значение (правда или ложь)
8 Ссылка на ячейку в виде объекта Range
16 Значение ошибки, например, #N/A
64 Массив значений

Используйте InputBox для отображения простого диалогового окна, что позволит вам вводить данные, которое можно будет использоваться в макросе. Диалоговое окно имеет кнопку ОК и кнопку Отмена. При выборе кнопки ОКInputBox возвращает значение, введенное в диалоговом окне. При выборе кнопки ОтменаInputBox возвращает значение Ложь.

Если значение Type равно 0, InputBox возвращает формулу в виде текста, например, =2*PI()/360 . Если в формуле есть все ссылки, они возвращаются в качестве ссылки в стиле A1. (Используйте ConvertFormula для преобразования стиля ссылок.)

Если значение Type равно 8, InputBox возвращает объект Range. Необходимо использовать оператор Set, чтобы назначить результат для объекта Range, как показано в приведенном ниже примере.

Если не используется оператор Set, для переменной устанавливается значение в диапазоне, а не сам объект Range.

Если вы используете метод InputBox для запроса формулы у пользователя, необходимо использовать свойство FormulaLocal, чтобы назначить формулу для объекта Range. Ввод формулы будет выполняться на языке пользователя.

Метод InputBox отличается от функции InputBox тем, что он позволяет выполнять выборочную проверку вводимых пользователем значений и его можно использовать с объектами, значениями ошибок и формулами Excel. Обратите внимание, что Application.InputBox вызывает метод InputBox; InputBox без квалификатора объекта вызывает функцию InputBox.

Пример

В этом примере у пользователя запрашивается число.

В этом примере пользователю предлагается выбрать ячейку на Листе1. В примере используется аргумент Type, чтобы гарантировать. что возвращаемое значение будет допустимой ссылкой на ячейку (объект Range).

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

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

VBA Excel. Первая форма (для начинающих)

Пример создания пользовательской формы в редакторе 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», используйте в модуле рабочего листа следующий код:

Источник

В этой заметке описываются методы создания пользовательских диалоговых окон, которые существенно расширяют стандартные возможности Excel. Диалоговые окна – это наиболее важный элемент пользовательского интерфейса в Windows. Они применяются практически в каждом приложении Windows, и большинство пользователей неплохо представляет, как они работают. Разработчики Excel создают пользовательские диалоговые окна с помощью пользовательских форм (UserForm). Кроме того, в VBA имеются средства, обеспечивающие создание типовых диалоговых окон.[1]

Рис. 1. Работа процедуры GetName

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

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

Использование окон ввода данных

Окно ввода данных — это простое диалоговое окно, которое позволяет пользователю ввести одно значение. Например, можно применить окно ввода данных, чтобы предоставить пользователю возможность ввести текст, число или диапазон значений. Для создания окна ввода предназначены две функции InputBox: одна— в VBA, а вторая является методом объекта Application.

Функция InputBox в VBA

Функция имеет следующий синтаксис:

InputBox(запрос [, заголовок] [, по_умолчанию] [, xpos] [, ypos] [, справка, раздел])

  • Запрос. Указывает текст, отображаемый в окне ввода (обязательный параметр).
  • Заголовок. Определяет заголовок окна ввода (необязательный параметр).
  • По_умолчанию. Задает значение, которое отображается в окне ввода по умолчанию (необязательный параметр).
  • xpos, ypos. Определяют координаты верхнего левого угла окна ввода на экране (необязательные параметры).
  • Справка, раздел. Указывают файл и раздел в справочной системе (необязательные параметры).

Функция InputBox запрашивает у пользователя одно значение. Она всегда возвращает строку, поэтому результат нужно будет преобразовать в числовое значение. Текст, отображаемый в окне ввода, может достигать 1024 символов (длину допускается изменять в зависимости от ширины используемых символов). Если определить раздел справочной системы, то в диалоговом окне будет отображена кнопка Справка.

Процедура GetName запрашивает у пользователя полное имя (имя и фамилию). Затем программа выделяет имя и отображает приветствие в окне сообщения (см. рис. 1; код функции можно найти в файле VBA inputbox.xlsm).

Sub GetName()

    Dim UserName As String

    Dim FirstSpace As Integer

    Do Until UserName <> «»

        UserName = InputBox(«Укажите имя и фамилию: «, _

            «Назовите себя»)

    Loop

    FirstSpace = InStr(UserName, » «)

    If FirstSpace <> 0 Then

        UserName = Left(UserName, FirstSpace 1)

    End If

    MsgBox «Привет « & UserName

End Sub

Обратите внимание: функция InputBox вызывается в цикле Do Until. Это позволяет убедиться в том, что данные введены в окно. Если пользователь щелкнет на кнопке Отмена или не введет текст, то переменная UserName будет содержать пустую строку, а окно ввода данных появится повторно. Далее в процедуре будет предпринята попытка получить имя пользователя путем поиска первого символа пробела (для этого применяется функция InStr). Таким образом, можно воспользоваться функцией Left для получения всех символов, расположенных слева от символа пробела. Если символ пробела не найден, то используется все введенное имя.

Если строка, предоставленная в качестве результата выполнения функции InputBox, выглядит как число, ее можно преобразовать с помощью функции VBA Val.

В процедуре GetWord пользователю предлагается ввести пропущенное слово (рис. 2). Этот пример также иллюстрирует применение именованных аргументов (р и t). Текст запроса выбирается из ячейки А1 рабочего листа.

Sub GetWord()

    Dim TheWord As String

    Dim p As String

    Dim t As String

    p = Range(«A1»)

    t = «Какое слово пропущено?»

    TheWord = InputBox(prompt:=p, Title:=t)

    If UCase(TheWord) = «ВОДОКАЧКУ» Then

        MsgBox «Верно.»

    Else

        MsgBox «Не верно.»

    End If

End Sub

Рис. 2. Использование функции VBA inputBox, отображающей запрос

Метод Excel InputBox

Метод Excel InputBox по сравнению с функцией VBA InputBox предоставляет три преимущества:

  • возможность задать тип возвращаемого значения;
  • возможность указать диапазон листа путем выделения с помощью мыши;
  • автоматическая проверка правильности введенных данных.

Метод InputBox имеет следующий синтаксис.

InputBox(запрос, [, заголовок], [, по_умолчанию], [, слева], [, сверху], [, справка, раздел], [, тип])

  • Запрос. Указывает текст, отображаемый в окне ввода (обязательный параметр).
  • Заголовок. Определяет заголовок окна ввода (необязательный параметр).
  • По_умолчанию. Задает значение, которое отображается в окне ввода по умолчанию (необязательный параметр).
  • Слева, сверху. Определяют координаты верхнего левого угла окна ввода на экране (необязательные параметры).
  • Справка, раздел. Указывают файл и раздел в справочной системе (необязательные параметры).
  • Тип. Указывает код типа данных, который будет возвращаться методом (необязательный параметр; значения см. рис. 3).

Рис. 3. Коды типов данных, возвращаемые методом Excel InputBox

Используя сумму приведенных выше значений, можно возвратить несколько типов данных. Например, для отображения окна ввода, которое принимает текстовый или числовой тип данных, установите код равным 3 (1 + 2 или число + текст). Если в качестве кода типа данных применить значение 8, то пользователь сможет ввести в поле адрес ячейки или диапазона ячеек. Пользователь также можент выбрать диапазон на текущем рабочем листе.

В процедуре EraseRange используется метод InputBox. Пользователь может указать удаляемый диапазон (рис. 4). Адрес диапазона вводится в окно вручную, или выделяется мышью на листе. Метод InputBox с кодом 8 возвращает объект Range (обратите внимание на ключевое слово Set). После этого выбранный диапазон очищается (с помощью метода Clear). По умолчанию в поле окна ввода отображается адрес текущей выделенной ячейки. Если в окне ввода щелкнуть на кнопке Отмена, то оператор On Error завершит процедуру.

Sub EraseRange()

    Dim UserRange As Range

    On Error GoTo Canceled

    Set UserRange = Application.InputBox _

        (Prompt:=«Удаляемый диапазон:», _

        Title:=«Удаление диапазона», _

        Default:=Selection.Address, _

        Type:=8)

    UserRange.Clear

    UserRange.Select

Canceled:

End Sub

Рис. 4. Пример использования метода InputBox для выбора диапазона

Если в процедуре EraseRange ввести не диапазон адресов, то Excel отобразит сообщение (рис. 5) и позволит пользователю повторить ввод данных.

Рис. 5. Метод InputBox автоматически проверяет вводимые данные

Функция VBA MsgBox

Функция VBA MsgBox служит для отображения сообщения. Также она передает результат щелчка на кнопке ОК или Отмена). Синтаксис функции:

MsgBox(запрос[, кнопки][, заголовок][, справка, раздел])

  • Запрос. Определяет текст, который будет отображаться в окне сообщения (обязательный параметр).
  • Кнопки. Содержит числовое выражение (или константу), которое определяет кнопки, отображаемые в окне сообщения (необязательный параметр; рис. 6). Также можно задать кнопку по умолчанию.
  • Заголовок. Содержит заголовок окна сообщения (необязательный параметр).
  • Справка, раздел. Указывают файл и раздел справочной системы (необязательные параметры).

Рис. 6. Константы и значения, используемые для выбора кнопок в функции MsgBox

Первая группа значений (0–5) описывает номер и тип кнопок в диалоговом окне. Вторая группа (16, 32, 48, 64) описывает стиль значка. Третья группа (0, 256, 512) определяет, какая кнопка назначена по умолчанию. Четвертая группа (0, 4096) определяет модальность окна сообщения. Пятая указывает, показывать ли окно сообщений поверх других окон, устанавливает выравнивание и направление текста. В процессе сложения чисел для получения окончательного значения аргумента Buttons следует использовать только одно число из каждой группы.

Можно использовать функцию MsgBox в качестве процедуры (для отображения сообщения), а также присвоить возвращаемое этой функцией значение переменной. Функция MsgBox возвращает результат, представляющий кнопку, на которой щелкнул пользователь. В следующем примере отображается сообщение и не возвращается результат (код функций, приведенных в этом разделе см. также в файле VBA msgbox.xlsm).

Sub MsgBoxDemo()

    MsgBox «При выполнении макроса ошибок не произошло.»

End Sub

Чтобы получить результат из окна сообщения, присвойте возвращаемое функцией MsgBox значение переменной. В следующем коде используется ряд встроенных констант (рис. 7), которые упрощают управление возвращаемыми функцией MsgBox значениями.

Sub GetAnswer()

    Dim Ans As Integer

    Ans = MsgBox(«Продолжать?», vbYesNo)

    Select Case Ans

        Case vbYes

            ‘ … [код при Ans равно Yes]

        Case vbNo

            ‘ ... [код при Ans равно No]

    End Select

End Sub

Рис. 7. Константы, возвращаемые MsgBox

Функция MsgBox возвращает переменную, имеющую тип Integer. Вам необязательно использовать переменную для хранения результата выполнения функции MsgBox. Следующая процедура представляет собой вариацию процедуры GetAnswer.

Sub GetAnswer2()

    If MsgBox(«Продолжать?», vbYesNo) = vbYes Then

‘ … [код при Ans равно Yes]

    Else

... [код при Ans равно No]

    End If

End Sub

В следующем примере функции используется комбинация констант для отображения окна сообщения с кнопками Да, Нет и знаком вопроса (рис. 8). Вторая кнопка (Нет) используется по умолчанию. Для простоты константы добавлены в переменную Config.

Private Function ContinueProcedure() As Boolean

   Dim Config As Integer

   Dim Ans As Integer

   Config = vbYesNo + vbQuestion + vbDefaultButton2

   Ans = MsgBox(«Произошла ошибка. Продолжить?», Config)

   If Ans = vbYes Then ContinueProcedure = True _

      Else ContinueProcedure = False

End Function

Рис. 8. Параметр Кнопки функции MsgBox определяет кнопки, которые отображаются в окне сообщения

В файле VBA msgbox.xlsm функция ContinueProcedure в демонстрационных целях представлена в виде процедуры. Функция ContinueProcedure может вызываться из другой процедуры. Например, оператор

If Not ContinueProcedure() Then Exit Sub

вызывает функцию ContinueProcedure (которая отображает окно сообщения). Если функция возвращает значение ЛОЖЬ (т.е. пользователь щелкнул на кнопке Нет), то процедура будет завершена. В противном случае выполняется следующий оператор.

Если в сообщении необходимо указать разрыв строки (рис. 9), воспользуйтесь константой vbCrLf (или vbNewLine):

Sub MultiLine()

    Dim Msg As String

    Msg = «Это первая строка.» & vbCrLf & vbNewLine

    Msg = Msg & «Вторая строка.» & vbCrLf

    Msg = Msg & «Третья строка.»

    MsgBox Msg

End Sub

Рис. 9. Разбиение сообщения на несколько строк

Для включения в сообщение символа табуляции применяется константа vbTab. В процедуре ShowRange окно сообщения используется для отображения диапазона значений размером 10 строк на 3 столбца — ячейки А1:С10 (рис. 10). В этом случае столбцы разделены с помощью константы vbTab. Новые строки вставляются с помощью константы vbCrLf. Функция MsgBox принимает в качестве параметра строку, длина которой не превышает 1023 символов. Такая длина задает ограничение на количество ячеек, которое можно отобразить в сообщении.

Sub ShowRange()

    Dim Msg As String

    Dim r As Integer, c As Integer

    Msg = «»

    For r = 1 To 10

        For c = 1 To 3

            Msg = Msg & Cells(r, c).Text

            If c <> 3 Then Msg = Msg & vbTab

            Next c

            Msg = Msg & vbCrLf

        Next r

    MsgBox Msg

End Sub

Рис. 10. Текст в этом окне сообщения содержит символы табуляции и разрыва строк

Метод Excel GetOpenFilename

Если приложению необходимо получить от пользователя имя файла, то можно воспользоваться функцией InputBox, но этот подход часто приводит к возникновению ошибок. Более надежным считается использование метода GetOpenFilename объекта Application, который позволяет удостовериться, что приложение получило корректное имя файла (а также его полный путь). Данный метод позволяет отобразить стандартное диалоговое окно Открытие документа, но при этом указанный файл не открывается. Вместо этого метод возвращает строку, которая содержит путь и имя файла, выбранные пользователем. По окончании данного процесса с именем файла можно делать все что угодно. Синтаксис (все параметры необязательные):

Application.GetOpenFilename(фильтр_файла, индекс_фильтра, заголовок, множественный_выбор)

  • Фильтр_файла. Содержит строку, определяющую критерий фильтрации файлов (необязательный параметр).
  • Индекс_фильтра. Указывает индексный номер того критерия фильтрации файлов, который используется по умолчанию (необязательный параметр).
  • Заголовок. Содержит заголовок диалогового окна (необязательный параметр). Если этот параметр не указать, то будет использован заголовок Открытие документа.
  • Множественный_выбор. Необязательный параметр. Если он имеет значение ИСТИНА, можно выбрать несколько имен файлов. Имя каждого файла заносится в массив. По умолчанию данный параметр имеет значение ЛОЖЬ.

Аргумент Фильтр_файла определяет содержимое раскрывающегося списка Тип файлов, находящегося в окне Открытие документа. Аргумент состоит из строки, определяющей отображаемое значение, а также строки действительной спецификации типа файлов, в которой находятся групповые символы. Оба элемента аргумента разделены запятыми. Если этот аргумент не указывать, то будет использовано значение, заданное по умолчанию: "Все файлы (*.*),*.*". Первая часть строки Все файлы (*.*) – то текст, отображаемый в раскрывающемся списке тип файлов. Вторая часть строки *.* указывает тип отображаемых файлов.

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

Filt = «Текстовые файлы (*.txt),*.txt,» & _

   «Файлы Lotus (*.prn),*.prn,» & _

   «Файлы, разделенные запятой (*.csv),*.csv,» & _

   «Файлы ASCII (*.asc),*.asc,» & _

   «Все файлы (*.*),*.*»

В следующем примере у пользователя запрашивается имя файла. При этом в поле типа файлов используются пять фильтров (код содержится в файле prompt for file.xlsm).

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

Sub GetImportFileName()

    Dim Filt As String

    Dim FilterIndex As Integer

    Dim FileName As Variant

    Dim Title As String

‘   Настройка списка фильтров

    Filt = «Text Files (*.txt),*.txt,» & _

            «Lotus Files (*.prn),*.prn,» & _

            «Comma Separated Files (*.csv),*.csv,» & _

            «ASCII Files (*.asc),*.asc,» & _

            «Все файлы (*.*),*.*»

   Отображает *.* по умолчанию

    FilterIndex = 3

‘   Настройка заголовка диалогового окна

    Title = «Выберите файл для импорта»

   Получение имени файла

    FileName = Application.GetOpenFilename _

        (FileFilter:=Filt, _

         FilterIndex:=FilterIndex, _

         Title:=Title)

‘   При отмене выйти из окна

    If FileName = False Then

        MsgBox «Файл не выбран.»

        Exit Sub

    End If

   Отображение полного имени и пути

    MsgBox «Вы выбрали « & FileName

End Sub

На рис. 11 показано диалоговое окно, которое выводится на экран после выполнения этой процедуры (по умолчанию предлагается фильтр *.csv).

Рис. 11. Метод GetOpenFilename отображает диалоговое окно, в котором выбирается файл

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

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

Sub GetImportFileName2()

    Dim Filt As String

    Dim FilterIndex As Integer

    Dim FileName As Variant

    Dim Title As String

    Dim i As Integer

    Dim Msg As String

‘   Установка списка фильтров файлов

    Filt = «Text Files (*.txt),*.txt,» & _

            «Lotus Files (*.prn),*.prn,» & _

            «Comma Separated Files (*.csv),*.csv,» & _

            «ASCII Files (*.asc),*.asc,» & _

            «All Files (*.*),*.*»

   Отображает *.* по умолчанию

    FilterIndex = 5

‘   Настройка заголовка диалогового окна

    Title = «Выберите файл для импорта»

   Получение имени файла

    FileName = Application.GetOpenFilename _

        (FileFilter:=Filt, _

         FilterIndex:=FilterIndex, _

         Title:=Title, _

         MultiSelect:=True)

‘   Выход в случае отмены работы с диалоговым окном

    If Not IsArray(FileName) Then

        MsgBox «Файл не выбран.»

        Exit Sub

    End If

   Отображение полного пути и имени файлов

    For i = LBound(FileName) To UBound(FileName)

        Msg = Msg & FileName(i) & vbCrLf

    Next i

    MsgBox «Было выбрано:» & vbCrLf & Msg

End Sub

Обратите внимание: переменная FileName определена как массив переменного типа (а не как строка в предыдущем примере). Причина заключается в том, что потенциально FileName может содержать массив значений, а не только одну строку.

Метод Excel GetSaveAsFilename

Данный метод отображает диалоговое окно Сохранение документа и дает пользователю возможность выбрать (или указать) имя сохраняемого файла. В результате возвращается имя файла, но никакие действия не предпринимаются. Синтаксис (все параметры необязательные):

Application.GetSaveAsFilename(начальное_имя, фильтр_файла, индекс_фильтра, заголовок, текст_кнопки)

  • Начальное_имя. Указывает предполагаемое имя файла.
  • Фильтр_файла. Содержит критерий фильтрации отображаемых в окне файлов.
  • Индекс_фильтра. Код критерия фильтрации файлов, который используется по умолчанию.
  • Заголовок. Определяет текст заголовка диалогового окна.

Получение имени папки

Для того чтобы получить имя файла, проще всего воспользоваться описанным выше методом GetOpenFileName. Но если нужно получить лишь имя папки (без названия файла), лучше воспользоваться методом объекта Excel FileDialog. Следующая процедура отображает диалоговое окно, в котором можно выбрать папку (см. также файл get directory.xlsm). С помощью функции MsgBox отображается имя выбранной папки (или сообщение Отменено).

Sub GetAFolder()

    With Application.FileDialog(msoFileDialogFolderPicker)

        .InitialFileName = Application.DefaultFilePath & «»

        .Title = «Выберите местоположение резервной копии.«

        .Show

        If .SelectedItems.Count = 0 Then

            MsgBox «Отменено»

        Else

            MsgBox .SelectedItems(1)

        End If

    End With

End Sub

Объект FileDialog позволяет определить начальную папку путем указания значения свойства InitialFileName. В примере в качестве начальной папки применяется путь к файлам Excel, заданный по умолчанию.

Отображение диалоговых окон Excel

Создаваемый вами код VBA может вызывать на выполнение многие команды Excel, находящиеся на ленте. И если в результате выполнения команды открывается диалоговое окно, ваш код может делать выбор в диалоговом окне (даже если само диалоговое окно не отображается). Например, следующая инструкция VBA эквивалентна выбору команды Главная –> Редактирование –> Найти и выделить –> Перейти и указанию диапазона ячеек А1:СЗ с последующим щелчком на кнопке ОК. Но само диалоговое окно Переход при этом не отображается (именно это и нужно).

Application.Goto Reference:=Range("А1:СЗ")

Иногда же приходится отображать встроенные окна Excel, чтобы пользователь мог сделать свой выбор. Для этого используется коллекция Dialogs объекта Application. Учтите, что в настоящее время компания Microsoft прекратила поддержу этого свойства. В предыдущих версиях Excel пользовательские меню и панели инструментов создавались с помощью объекта CommandBar. В версиях Excel 2007 и Excel 2010 этот объект по-прежнему доступен, хотя и работает не так, как раньше. Начиная с версии Excel 2007 возможности объекта CommandBar были существенно расширены. В частности, объект CommandBar можно использовать для вызова команд ленты с помощью VBA. Многие из команд, доступ к которым открывается с помощью ленты, отображают диалоговое окно. Например, следующая инструкция отображает диалоговое окно Вывод на экран скрытого листа (рис. 12; см. также файл ribbon control names.xlsm):

Application.CommandBars.ExecuteMso("SheetUnhide")

Рис. 12. Диалоговое окно, отображаемое в результате выполнения указанного выше оператора

Метод ExecuteMso принимает лишь один аргумент, idMso, который представляет элемент управления ленты. К сожалению, сведения о многих параметрах в справочной системе отсутствуют.

В файле ribbon control names.xlsm описаны все названия параметров команд ленты Excel. Поэкспериментируйте с параметрами, перечисленными в этой рабочей книге. Многие из них вызывают команды немедленно (без промежуточных диалоговых окон). Но большинство из них генерирует ошибку при использовании в неправильном контексте. Например, Excel отображает сообщение об ошибке, если команда Functionwizard вызывается в случае выбора диаграммы.

В результате выполнения следующего оператора отображается вкладка Шрифт диалогового окна Формат ячеек:

Application.CommandBars.ExecuteMso("FormatCellsFontDialog")

На самом деле пользоваться объектами CommandBar не стоит, поскольку вряд ли они будут поддерживаться в будущих версиях Excel.

Отображение формы ввода данных

Многие пользователи применяют Excel для управления списками, информация в которых ранжирована по строкам. В Excel поддерживается простой способ работы с подобными типами данных с помощью встроенных форм ввода данных, которые могут создаваться автоматически. Подобная форма предназначена для работы как с обычным диапазоном, так и с диапазоном, оформленным в виде таблицы (с помощью команды Вставка –> Таблицы –> Таблица). Пример формы ввода данных показан на рис. 13 (см. также файл data form example.xlsm).

Рис. 13. Некоторые пользователи предпочитают применять встроенные формы ввода данных Excel для ввода сведений; чтобы увеличить изображение кликните на нем правой кнопкой мыши и выберите Открыть картинку в новой вкладке

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

  1. Щелкните правой кнопкой мыши на панели быстрого доступа и в контекстном меню выберите параметр Настройка панели быстрого доступа.
  2. На экране появится вкладка Панель быстрого доступа диалогового окна Параметры Excel.
  3. В раскрывающемся списке Выбрать команды из выберите параметр Команды не на ленте.
  4. В появившемся списке выберите параметр Форма.
  5. Щелкните на кнопке Добавить для добавления выбранной команды на панель быстрого доступа.
  6. Щелкните на кнопке ОК для закрытия диалогового окна Параметры Excel.

После выполнения перечисленных выше действий на панели быстрого доступа появится новый значок.

Для работы с формой ввода данных следует структурировать данные таким образом, чтобы Excel распознавал их в виде таблицы. Начните с указания заголовков столбцов в первой строке диапазона вводимых данных. Выделите любую ячейку в таблице и щелкните на кнопке Форма панели быстрого доступа. Excel отображает диалоговое окно, в котором будут вводиться данные. Для перемещения между текстовыми полями в целях ввода информации используйте клавишу <Tab>. Если ячейка содержит формулу, результат вычислений отображается в виде текста (а не в формате поля ввода данных). Другими словами, невозможно изменить формулы с помощью формы ввода данных.

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

Используйте метод ShowDataForm для отображения формы ввода данных Excel. Единственное требование заключается в том, что активная ячейка должна находиться в диапазоне. Следующий код активизирует ячейку А1 (в таблице), а затем отображает форму ввода данных.

Sub DisplayDataForm()

    Range(«A1»).Select

    ActiveSheet.ShowDataForm

End Sub

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

Excel VBA InputBox: Step-by-Step Guide and 9 Examples to Create an Input Box with MacrosIn this VBA Tutorial, you learn how to create input boxes with both the InputBox function and the Application.InputBox method. This includes:

  1. How to create an InputBox.
  2. How to create an InputBox with multiple lines.
  3. How to create an InputBox that works with a specific type of data.
  4. How to handle the cases where the user clicks the Cancel button of the InputBox.

This VBA InputBox Tutorial is accompanied by an Excel workbook containing the macros I use in the examples below. You can get immediate access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA InputBox Tutorial workbook example

Related VBA and Macro Tutorials

The following VBA and Macro Tutorials may help you better understand and implement the contents below:

  • General VBA constructs and structures:
    • Read a Macro Tutorial for beginners here.
    • Learn the definitions of several basic and important VBA terms here.
    • Learn how to specify macro security settings here.
    • Learn how to work with the Visual Basic Editor here.
    • Learn about the Excel VBA Object Model here.
    • Learn how to refer to cell ranges here.
    • Learn how to create Sub procedures here.
    • Learn how to work with object properties here.
    • Learn how to work with object methods here.
    • Learn how to declare and work with variables here.
    • Learn how to work with data types here.
    • Learn how to work with functions here.
    • Learn how to work with loops here.
    • Learn how to work with arrays here.
  • Practical VBA applications and macro examples:
    • Learn how to work with worksheets here.
    • Learn how to convert strings to numbers here.
    • Learn how to create message boxes here.
    • Learn how to create UserForms here.

You can find additional VBA and Macro Tutorials in the Archives.

#1: Create InputBox with InputBox function

VBA code to create InputBox with InputBox function

To create a basic InputBox with the VBA InputBox function, use a statement with the following structure:

InputBoxVariable = InputBox(Prompt:=PromptString, Title:=TitleString, Default:=DefaultInputString)

Process to create InputBox with InputBox function

To create a basic InputBox with the VBA InputBox function, follow these steps:

  1. Create an input box with the InputBox function (InputBox(…)).
  2. Assign the value returned by the InputBox function to a variable (InputBoxVariable = InputBox(…)).

VBA statement explanation

Item: InputBoxVariable

InputBoxVariable is the variable you want to hold the value returned by the InputBox function.

The InputBox function returns a String.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: InputBox(…)

The InputBox function:

  1. Displays an input box;
  2. Waits for the user to either (i) input text and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns a string with the contents of the text box in the input box (when the user clicks OK or presses Enter).

If you want to handle the cases where the user clicks on the Cancel button or presses Esc, please refer to the appropriate section of this Tutorial.

Item: Prompt:=PromptString

The Prompt argument of the InputBox function is a string displayed as the message in the input box. Prompt is a required argument.

You generally specify PromptString as a string expression.

The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Item: Title:=TitleString

The Title argument of the InputBox function is a string expression displayed as the title in the title bar of the input box.

Title is an optional argument. If you omit the Title argument, the title of the input box is “Microsoft Excel”.

You generally specify TitleString as a string expression.

Item: Default:=DefaultInputString

The Default argument of the InputBox function is a string expression displayed inside the text box of the input box. DefaultInputString is, therefore, the default response.

Default is an optional argument. If you omit the Default argument, the text box is empty.

Macro example to create InputBox with InputBox function

The following macro example:

  1. Creates a basic input box with the InputBox function.
  2. Assigns the value returned by the InputBox function to a variable (myInputBoxVariable = inputBox(…)).
  3. Displays a message box with the value held by the variable.
Sub CreateInputBoxFunction()
    'source: https://powerspreadsheets.com/
    'creates an input box with the InputBox function
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxVariable As String

    '(1) create InputBox, and (2) assign value returned by InputBox function to variable
    myInputBoxVariable = inputBox(Prompt:="Create Excel VBA InputBox", Title:="This is an Excel VBA InputBox", Default:="Enter VBA InputBox value here")

    'display message box with value held by variable
    MsgBox "Your input was: " & myInputBoxVariable

End Sub

Effects of executing macro example to create InputBox with InputBox function

The following GIF illustrates the results of executing the macro example. As expected, Excel displays a basic input box using the InputBox function.

VBA creates input box with InputBox function

#2: Create InputBox with Application.InputBox method

VBA code to create InputBox with Application.InputBox method

To create a basic InputBox with the VBA Application.InputBox method, use a statement with the following structure:

InputBoxVariable = Application.InputBox(Prompt:=PromptString, Title:=TitleString, Default:=DefaultInput)

Process to create InputBox with Application.InputBox method

To create a basic InputBox with the VBA Application.InputBox method, follow these steps:

  1. Create an input box with the Application.InputBox method (Application.InputBox(…)).
  2. Assign the value returned by the Application.InputBox method to a variable (InputBoxVariable = Application.InputBox(…)).

VBA statement explanation

Item: InputBoxVariable

InputBoxVariable is the variable you want to hold the value returned by the Application.InputBox method.

The Application.InputBox method returns a Variant.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: Application.InputBox(…)

The Application.InputBox method:

  1. Displays an input box’
  2. Waits for the user to either (i) input information and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns the information entered in the dialog box (if the user clicks OK or presses Enter) or the False Boolean value (if the user clicks Cancel).
Item: Prompt:=PromptString

The Prompt parameter of the Application.InputBox method is a string displayed as the message in the input box. Prompt is a required parameter.

You generally specify PromptString as a string expression.

You can also specify PromptString as a number, a date or a Boolean. In such cases, Excel coerces the number, date or Boolean to a string.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Item: Title:=TitleString

The Title parameter of the Application.InputBox method is the title displayed in the title bar of the input box.

Title is an optional parameter. If you omit the Title parameter, the title of the input box is “Input”.

The Title parameter is of the Variant data type.

Item: Default:=DefaultInput

The Default parameter of the Application.InputBox method is the value displayed inside the text box of the input box. DefaultInput is, therefore, the default response.

Default is an optional parameter. If you omit the Default parameter, the text box is empty.

The Default parameter is of the Variant data type.

Macro example to create InputBox with Application.InputBox method

The following macro example:

  1. Creates a basic input box with the Application.InputBox method.
  2. Assigns the value returned by the Application.InputBox method to a variable (myInputBoxVariable = Application.inputBox(…)).
  3. Displays a message box with the value held by the variable.
Sub CreateInputBoxMethod()
    'source: https://powerspreadsheets.com/
    'creates an input box with the Application.InputBox method
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxVariable As Variant

    '(1) create InputBox, and (2) assign value returned by Application.InputBox method to variable
    myInputBoxVariable = Application.inputBox(Prompt:="Create Excel VBA InputBox", Title:="This is an Excel VBA InputBox", Default:="Enter VBA InputBox value here")

    'display message box with value held by variable
    MsgBox "Your input was: " & myInputBoxVariable

End Sub

Effects of executing macro example to create InputBox with Application.InputBox method

The following GIF illustrates the results of executing the macro example. As expected, Excel displays a basic input box using the Application.InputBox method.

VBA creates input box with Application.InputBox method

#3: Create InputBox with multiple lines using InputBox function

VBA code to create InputBox with multiple lines using InputBox function

To create an InputBox containing multiple lines with the VBA InputBox function, use a statement with the following structure:

InputBoxMultipleLinesVariable = inputBox(Prompt:=PromptString1 & NewLineCharacter & PromptString2 & ... & NewLineCharacter & PromptString#)

Process to create InputBox with multiple lines using InputBox function

To create an InputBox containing multiple lines with the VBA InputBox function, follow these steps:

  1. Create an input box with the InputBox function (InputBox(…)).
  2. Specify the message displayed in the message box (Prompt:=PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#) as an appropriately concatenated (with the & character) combination of:
    • Strings (PromptString1, PromptString2, …, PromptString#); and
    • Characters that create a new line or line break (NewLineCharacter).
  3. Assign the value returned by the InputBox function to a variable (InputBoxMultipleLinesVariable = InputBox(…)).

VBA statement explanation

Item: InputBoxMultipleLinesVariable

InputBoxMultipleLinesVariable is the variable you want to hold the value returned by the InputBox function.

The InputBox function returns a String.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: inputBox(…)

The InputBox function:

  1. Displays an input box;
  2. Waits for the user to either (i) input text and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns a string with the contents of the text box in the input box (when the user clicks OK or presses Enter).

If you want to handle the cases where the user clicks on the Cancel button or presses Esc, please refer to the appropriate section of this Tutorial.

Item: Prompt:=PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#

The Prompt argument of the InputBox function is a string displayed as the message in the input box. Prompt is a required argument.

You generally specify Prompt as a string expression.

The maximum length of Prompt is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters you work with.

To create an input box with multiple lines, you build the string expression assigned to Prompt by concatenating as many strings (PromptString1, PromptString2, …, PromptString#) and new line characters (NewLineCharacter) as required. For these purposes:

  • PromptString1, PromptString2, …, PromptString# are the strings (excluding the new line characters) that determine the message in the input box.
  • The & operator carries out string concatenation. Therefore, & concatenates the different strings and new line characters.
  • NewLineCharacter is a character or character combination returning 1 of the following:
    • Carriage return.
    • Linefeed.
    • Carriage return linefeed combination.
    • New line (which is platform specific).

Specify NewLineCharacter using any of the constants or character codes (with the Chr function) listed below:

Constant Equivalent Chr function General description
vbLf Chr(10) Linefeed
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return linefeed combination
vbNewLine Chr(13) & Chr(10) in Excel for Windows or Chr(13) in Excel for Mac New line character, which is platform specific

Macro example to create InputBox with multiple lines using InputBox function

The following macro example:

  1. Creates an input box containing multiple lines (Create Excel VBA InputBox” & vbNewLine & “with multiple lines) with the InputBox function.
  2. Assigns the value returned by the InputBox function to a variable (myInputBoxMultipleLinesVariable = inputBox(…)).
  3. Displays a message box with the value held by the variable.
Sub CreateInputBoxFunctionMultipleLines()
    'source: https://powerspreadsheets.com/
    'creates an input box with multiple lines using the InputBox function
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxMultipleLinesVariable As String

    '(1) create InputBox with multiple lines, and (2) assign value returned by InputBox function to variable
    myInputBoxMultipleLinesVariable = inputBox(Prompt:="Create Excel VBA InputBox" & vbNewLine & "with multiple lines")

    'display message box with value held by variable
    MsgBox "Your input was: " & myInputBoxMultipleLinesVariable

End Sub

Effects of executing macro example to create InputBox with multiple lines using InputBox function

The following GIF illustrates the results of executing the macro example. As expected, Excel displays an input box containing multiple lines using the InputBox function.

VBA creates InputBox with multiple lines

#4: Create InputBox with multiple lines using Application.InputBox method

VBA code to create InputBox with multiple lines using Application.InputBox method

To create an InputBox containing multiple lines with the VBA Application.InputBox method, use a statement with the following structure:

InputBoxMultipleLinesVariable = Application.InputBox(Prompt:=PromptString1 & NewLineCharacter & PromptString2 & ... & NewLineCharacter & PromptString#)

Process to create InputBox with multiple lines using Application.InputBox method

To create an InputBox containing multiple lines with the VBA Application.InputBox method, follow these steps:

  1. Create an input box with the Application.InputBox method (Application.InputBox(…)).
  2. Specify the message displayed in the message box (Prompt:=PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#) as an appropriately concatenated (with the & character) combination of:
    • Strings (PromptString1, PromptString2, …, PromptString#); and
    • Characters that create a new line or line break (NewLineCharacter).
  3. Assign the value returned by the Application.InputBox method to a variable (InputBoxMultipleLinesVariable = Application.InputBox(…)).

VBA statement explanation

Item: InputBoxMultipleLinesVariable

InputBoxMultipleLinesVariable is the variable you want to hold the value returned by the Application.InputBox method.

The Application.InputBox method returns a Variant.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: Application.InputBox(…)

The Application.InputBox method:

  1. Displays an input box’
  2. Waits for the user to either (i) input information and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns the information entered in the dialog box (if the user clicks OK or presses Enter) or the False Boolean value (if the user clicks Cancel).
Item: Prompt:=PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#

The Prompt parameter of the Application.InputBox method is a string displayed as the message in the input box. Prompt is a required parameter.

You generally specify Prompt as a string expression. You can also specify Prompt as a number, a date or a Boolean. In such cases, Excel coerces the number, date or Boolean to a string.

To create an input box with multiple lines, you build the expression assigned to Prompt by concatenating as many strings (PromptString1, PromptString2, …, PromptString#) and new line characters (NewLineCharacter) as required. For these purposes:

  • PromptString1, PromptString2, …, PromptString# are the strings (excluding the new line characters) that determine the message in the input box.
  • The & operator carries out string concatenation. Therefore, & concatenates the different strings and new line characters.
  • NewLineCharacter is a character or character combination returning 1 of the following:
    • Carriage return.
    • Linefeed.
    • Carriage return linefeed combination.
    • New line (which is platform specific).

Specify NewLineCharacter using any of the constants or character codes (with the Chr function) listed below:

Constant Equivalent Chr function General description
vbLf Chr(10) Linefeed
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return linefeed combination
vbNewLine Chr(13) & Chr(10) in Excel for Windows or Chr(13) in Excel for Mac New line character, which is platform specific

Macro example to create InputBox with multiple lines using Application.InputBox method

The following macro example:

  1. Creates an input box containing multiple lines (Create Excel VBA InputBox” & vbNewLine & “with multiple lines) with the Application.InputBox method.
  2. Assigns the value returned by the Application.InputBox method to a variable (myInputBoxMultipleLinesVariable = Application.inputBox(…)).
  3. Displays a message box with the value held by the variable.
Sub CreateInputBoxMethodMultipleLines()
    'source: https://powerspreadsheets.com/
    'creates an input box with multiple lines using the Application.InputBox method
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxMultipleLinesVariable As Variant

    '(1) create InputBox with multiple lines, and (2) assign value returned by Application.InputBox method to variable
    myInputBoxMultipleLinesVariable = Application.inputBox(Prompt:="Create Excel VBA InputBox" & vbNewLine & "with multiple lines")

    'display message box with value held by variable
    MsgBox "Your input was: " & myInputBoxMultipleLinesVariable

End Sub

Effects of executing macro example to create InputBox with multiple lines using Application.InputBox method

The following GIF illustrates the results of executing the macro example. As expected, Excel displays an input box containing multiple lines using the Application.InputBox method.

VBA creates input box with multiple lines using Application.InputBox method

#5: Create InputBox that works with a specific data type using InputBox function

VBA code to create InputBox that works with a specific data type using InputBox function

To create an InputBox that works with a specific data type with the VBA InputBox function, use a macro with the following statement structure:

InputBoxTypeVariable = InputBox(Prompt:=PromptString)
If IsFunction(InputBoxTypeVariable) Then
    StatementsIfInputIsType
Else
    StatementsIfInputIsNotType
End If

Process to create InputBox that works with a specific data type using InputBox function

To create an InputBox that works with a specific data type with the VBA InputBox function, follow these steps:

  1. Create an input box with the InputBox function (InputBox(…)).
  2. Assign the value returned by the InputBox function to a variable (InputBoxTypeVariable = InputBox(…)).
  3. Use an If… Then… Else statement for the following:
    • Testing whether the type of data held by the variable is the one you want to work with (IsFunction(InputBoxTypeVariable)).
    • Executing the appropriate group of statements depending on whether the type of data held by the variable is the one you want to work with (StatementsIfInputIsType) or not (StatementsIfInputIsNotType).

VBA statement explanation

Line #1: InputBoxTypeVariable = InputBox(Prompt:=PromptString)

Item: InputBoxTypeVariable

InputBoxTypeVariable is the variable you want to hold the value returned by the InputBox function.

The InputBox function returns a String.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: InputBox(…)

The InputBox function:

  1. Displays an input box;
  2. Waits for the user to either (i) input text and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns a string with the contents of the text box in the input box (when the user clicks OK or presses Enter).

If you want to handle the cases where the user clicks on the Cancel button or presses Esc, please refer to the appropriate section of this Tutorial.

Item: Prompt:=PromptString

The Prompt argument of the InputBox function is a string displayed as the message in the input box. Prompt is a required argument.

You generally specify PromptString as a string expression.

The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Lines #2, #4 and #6: If IsFunction(InputBoxTypeVariable) Then | Else | End If

Item: If… Then… Else… End If

The If… Then… Else statement conditionally executes a group of statements (StatementsIfInputIsType or StatementsIfInputIsNotType) depending on the value of an expression (Isfunction(InputBoxTypeVariable)).

Item: IsFunction(InputBoxTypeVariable)

The condition of the If… Then… Else statement is an expression returning True or False.

When you work with an input box and a specific data type using this macro structure, you can check the type of data held by InputBoxTypeVariable by working with certain VBA built-in functions (an IsFunction), as appropriate. These include the following functions:

Function Returns True if InputBoxTypeVariable… Returns False if InputBoxTypeVariable…
IsDate Is a date or recognizable as a valid date Isn’t date or isn’t recognizable as a valid date
IsError Is an error value Isn’t an error value
IsNumeric Can be evaluated/recognized as a number Can’t be evaluated/recognized as a number

Line #3: StatementsIfInputIsType

Statements executed if the tested condition (IsFunction(InputBoxTypeVariable)) returns True. In other words, these statements are executed if the input entered by the user in the input box is of the appropriate type.

Line #5: StatementsIfInputIsNotType

Statements executed if the tested condition (IsFunction(InputBoxTypeVariable)) returns False. In other words, these statements are executed if the input entered by the user in the input box isn’t of the appropriate type.

Macro example to create InputBox that works with a specific data type using InputBox function

The following macro example:

  1. Creates an input box with the InputBox function.
  2. Assigns the value returned by the InputBox function to a variable (myInputBoxTypeVariable = inputBox(…)).
  3. Checks whether the value held by the variable is numeric (IsNumeric(myInputBoxTypeVariable)).
    • If the value is numeric, displays a message box with the value held by the variable.
    • If the value isn’t numeric, displays a message box asking the user to try again and enter a number.
Sub CreateInputBoxFunctionDataType()
    'source: https://powerspreadsheets.com/
    'creates an input box that works with a number using the InputBox function
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxTypeVariable As String

    '(1) create InputBox that works with a number, and (2) assign value returned by InputBox function to variable
    myInputBoxTypeVariable = inputBox(Prompt:="Create Excel VBA InputBox that works with a number")

    'check if user entered a number and, if appropriate, execute statements
    If IsNumeric(myInputBoxTypeVariable) Then

        'display message box with value held by variable
        MsgBox "Your input was: " & myInputBoxTypeVariable

    'if user didn't enter a number, execute statements
    Else

        'display message box confirming that user didn't enter a number
        MsgBox "Please try again and enter a number"

    End If

End Sub

Effects of executing macro example to create InputBox that works with a specific data type using InputBox function

The following GIF illustrates the results of executing the macro example. As expected:

  • Excel identifies whether the input box created with the InputBox function contains a number; and
  • Displays the appropriate message box.

VBA creates InputBox that works with numbers

#6: Create InputBox that works with a specific data type using Application.InputBox method

VBA code to create InputBox that works with a specific data type using Application.InputBox method

To create an InputBox that works with a specific data type with the VBA Application.InputBox method, use a statement with the following structure:

InputBoxTypeVariable = Application.InputBox(Prompt:=PromptString, Type:=TypeValue)

Process to create InputBox that works with a specific data type using Application.InputBox method

To create an InputBox that works with a specific data type with the VBA Application.InputBox method, follow these steps:

  1. Create an input box with the Application.InputBox method (Application.InputBox(…)).
  2. Specify the data type you want to work with by working with the Type parameter of the Application.InputBox method (Type:=TypeValue).
  3. Assign the value returned by the Application.InputBox method to a variable (InputBoxTypeVariable = Application.InputBox(…)).

VBA statement explanation

Item: InputBoxTypeVariable

InputBoxTypeVariable is the variable you want to hold the value returned by the Application.InputBox method.

The Application.InputBox method returns a Variant.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: Application.InputBox(…)

The Application.InputBox method:

  1. Displays an input box’
  2. Waits for the user to either (i) input information and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns the information entered in the dialog box (if the user clicks OK or presses Enter) or the False Boolean value (if the user clicks Cancel).
Item: Prompt:=PromptString

The Prompt parameter of the Application.InputBox method is a string displayed as the message in the input box. Prompt is a required parameter.

You generally specify PromptString as a string expression.

You can also specify PromptString as a number, a date or a Boolean. In such cases, Excel coerces the number, date or Boolean to a string.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Item: Type:=TypeValue

The Type parameter of the Application.InputBox method specifies the data type returned.

Set the Type parameter using the values listed below. If required, you can set the Type parameter to be a sum of several of these values.

Value Basic description Additional comments
0 Formula Application.InputBox returns the formula in the form of text. Cell references inside the formula are returned as A1-style references.
1 Number  
2 Text  
4 Boolean  
8 Range object Use the Set statement to assign the Range object returned by Application.InputBox to an object variable.
16 Error  
64 Array of values  

Type is an optional parameter. If you omit the Type parameter, the Application.InputBox method returns text.

Macro example to create InputBox that works with a specific data type using Application.InputBox method

The following macro example:

  1. Creates an input box that returns a number (Type:=1) with the Application.InputBox method.
  2. Assigns the value returned by the Application.InputBox method to a variable (myInputBoxTypeVariable = Application.inputBox(…)).
  3. Displays a message box with the value held by the variable.
Sub CreateInputBoxMethodDataType()
    'source: https://powerspreadsheets.com/
    'creates an input box that works with a number using the Application.InputBox method
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxTypeVariable As Variant

    '(1) create InputBox that works with a number, and (2) assign value returned by Application.InputBox method to variable
    myInputBoxTypeVariable = Application.inputBox(Prompt:="Create Excel VBA InputBox that works with a number", Type:=1)

    'display message box with value held by variable
    MsgBox "Your input was: " & myInputBoxTypeVariable

End Sub

Effects of executing macro example to create InputBox that works with a specific data type using Application.InputBox method

The following GIF illustrates the results of executing the macro example. As expected:

  • Excel identifies whether the input box created with the Application.InputBox method contains a number; and
  • If the entered input isn’t a number, displays a warning.

VBA creates input box that works with numeric values using Application.InputBox

#7: Create InputBox and check if user clicks Cancel button with InputBox function

VBA code to create InputBox and check if user clicks Cancel button with InputBox function

To create an InputBox with the VBA InputBox function and check if the user clicks Cancel, use a macro with the following statement structure:

InputBoxCancelVariable = InputBox(Prompt:=PromptString)
If StrPtr(InputBoxCancelVariable) = 0 Then
    StatementsIfCancel
ElseIf InputBoxCancelVariable = "" Then
    StatementsIfNoInput
Else
    StatementsIfInputAndOK
End If

Process to create InputBox and check if user clicks Cancel button with InputBox function

To create an InputBox that works with a specific data type with the VBA InputBox function, follow these steps:

  1. Create an input box with the InputBox function (InputBox(…)).
  2. Assign the value returned by the InputBox function to a variable (InputBoxCancelVariable = InputBox(…)).
  3. Use an If… Then… Else statement for the following:
    • Testing whether the user clicked Cancel (StrPtr(InputBoxCancelVariable) = 0) or entered no input prior to clicking OK (InputBoxCancelVariable = “”).
    • Executing the appropriate group of statements depending on whether the user clicked Cancel (StatementsIfCancel), entered no input prior to clicking OK (StatementsIfNoInput) or entered input and clicked OK (StatementsIfInputAndOK).

VBA statement explanation

Line #1: InputBoxCancelVariable = InputBox(Prompt:=PromptString)

Item: InputBoxCancelVariable

InputBoxCancelVariable is the variable you want to hold the value returned by the InputBox function.

The InputBox function returns a String.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: InputBox(…)

The InputBox function:

  1. Displays an input box;
  2. Waits for the user to either (i) input text and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns a string with the contents of the text box in the input box (when the user clicks OK or presses Enter).

According to the Microsoft Developer Network, the InputBox function returns a zero-length string (“”) when the user clicks Cancel (or presses Esc). When checking if the user clicks Cancel using this macro structure, you rely on a quirk of the InputBox function which allows you to work with StrPtr.

Item: Prompt:=PromptString

The Prompt argument of the InputBox function is a string displayed as the message in the input box. Prompt is a required argument.

You generally specify PromptString as a string expression.

The maximum length of PromptString is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters within PromptString.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Lines #2, #6 and #8: If StrPtr(InputBoxCancelVariable) = 0 Then | Else | End If

Item: If… Then… Else… End If

The If… Then… Else statement conditionally executes a group of statements (StatementsIfCancel, StatementsIfNoInput or StatementsIfInputAndOK) depending on the value of an expression (StrPtr(InputBoxCancelVariable) = 0 or InputBoxCancelVariable = “”).

Item: StrPtr(InputBoxCancelVariable) = 0

The condition of the If… Then… Else statement is an expression returning True or False.

When you check if the user clicks the Cancel button using this macro structure, you can work with the StrPtr function. StrPtr is an undocumented function. You can usually work with the StrPtr function to obtain the address of a variable.

When the user clicks Cancel, no string is assigned to InputBoxCancelVariable. Therefore, if the user clicks Cancel, StrPtr(InputBoxCancelVariable) = 0 returns True.

Line #3: StatementsIfCancel

Statements executed if the tested condition (StrPtr(InputBoxCancelVariable) = 0) returns True. In other words, these statements are executed if the user clicks Cancel.

Line #4: ElseIf InputBoxCancelVariable = “” Then

Item: ElseIf… Then

The If… Then… Else statement conditionally executes a group of statements (StatementsIfCancel, StatementsIfNoInput or StatementsIfInputAndOK) depending on the value of an expression (StrPtr(InputBoxCancelVariable) = 0 or InputBoxCancelVariable = “”).

Item: InputBoxCancelVariable = “”

The condition-n of the If… Then… Else statement is an expression returning True or False.

You can check if the user didn’t enter any input prior to clicking OK by testing whether InputBoxCancelVariable holds a zero-length string (“”). In other words, if the user doesn’t enter any input and clicks the OK button, InputBoxCancelVariable = 0 returns True.

Line #5: StatementsIfNoInput

Statements executed if the tested condition (InputBoxCancelVariable = “”) returns True. In other words, these statements are executed if the user doesn’t enter any input and clicks the OK button.

Line #7: StatementsIfInputAndOK

Statements executed if none of the tested conditions (StrPtr(InputBoxCancelVariable) = 0 or InputBoxCancelVariable = “”) return True. In other words, these statements are executed if the user enters an input and clicks the OK button.

Macro example to create InputBox and check if user clicks Cancel button with InputBox function

The following macro example:

  1. Creates an input box with the InputBox function.
  2. Assigns the value returned by the InputBox function to a variable (myInputBoxCancelVariable = inputBox(…)).
  3. Checks whether user clicked Cancel (StrPtr(myInputBoxCancelVariable) = 0). If the user clicked Cancel, displays a message box confirming this.
  4. If the user didn’t click Cancel, checks whether the user entered no input prior to clicking OK (myInputBoxCancelVariable = “”). If the user entered no input prior to clicking OK, displays a message box confirming this.
  5. If the user entered input and clicked OK, displays a message box with the value held by the variable.
Sub CreateInputBoxFunctionCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates an input box with the InputBox function, and (2) handles case where user clicks Cancel button
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxCancelVariable As String

    '(1) create InputBox, and (2) assign value returned by InputBox function to variable
    myInputBoxCancelVariable = inputBox(Prompt:="Create Excel VBA InputBox and work with Cancel button")

    'check if user clicked Cancel button and, if appropriate, execute statements
    If StrPtr(myInputBoxCancelVariable) = 0 Then

        'display message box confirming that user clicked Cancel button
        MsgBox "You clicked the Cancel button"

    'check if user entered no input and, if appropriate, execute statements
    ElseIf myInputBoxCancelVariable = "" Then

        'display message box confirming that user entered no input
        MsgBox "You didn't enter an input"

    'if user didn't click Cancel button and entered input, execute statements
    Else

        'display message box with value held by variable
    MsgBox "Your input was: " & myInputBoxCancelVariable

    End If

End Sub

Effects of executing macro example to create InputBox and check if user clicks Cancel button with InputBox function

The following GIF illustrates the results of executing the macro example. As expected:

  • Excel displays an input box created with the InputBox function.
  • The macro identifies whether the user:
    • Clicks the Cancel button;
    • Enters no input prior to clicking OK; or
    • Enters input and clicks OK.
  • Excel displays the appropriate message box depending on the actions taken by the user.

VBA creates InputBox and checks if user clicked Cancel

#8: Create InputBox and check if user clicks Cancel button with Application.InputBox method

VBA code to create InputBox and check if user clicks Cancel button with Application.InputBox method

To create an InputBox with the VBA Application.InputBox method and check if the user clicks Cancel, use a macro with the following statement structure:

InputBoxCancelVariable = Application.InputBox(Prompt:=PromptString)
If (TypeName(InputBoxCancelVariable) = "Boolean") And (InputBoxCancelVariable = "False") Then
    StatementsIfCancel
ElseIf InputBoxCancelVariable = "" Then
    StatementsIfNoInput
Else
    StatementsIfInputAndOK
End If

Process to create InputBox and check if user clicks Cancel button with Application.InputBox method

To create an InputBox with the VBA Application.InputBox method and check if the user clicks Cancel, follow these steps:

  1. Create an input box with the Application.InputBox method (Application.InputBox(…)).
  2. Assign the value returned by the Application.InputBox method to a variable (InputBoxCancelVariable = Application.InputBox(…)).
  3. Use an If… Then… Else statement for the following:
    • Testing whether the user clicked Cancel ((TypeName(InputBoxCancelVariable) = “Boolean”) And (InputBoxCancelVariable = “False”)) or entered no input prior to clicking OK (InputBoxCancelVariable = “”).
    • Executing the appropriate group of statements depending on whether the user clicked Cancel (StatementsIfCancel), entered no input prior to clicking OK (StatementsIfNoInput) or entered input and clicked OK (StatementsIfInputAndOK).

VBA statement explanation

Line #1: InputBoxCancelVariable = Application.InputBox(Prompt:=PromptString)

Item: InputBoxCancelVariable

InputBoxCancelVariable is the variable you want to hold the value returned by the Application.InputBox method.

The Application.InputBox method returns a Variant.

Item: =

The = operator assigns a value to a variable or property.

Use the = operator to assign the value returned by the InputBox function (InputBox(…)) to InputBoxVariable.

Item: Application.InputBox(…)

The Application.InputBox method:

  1. Displays an input box’
  2. Waits for the user to either (i) input information and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns the information entered in the dialog box (if the user clicks OK or presses Enter) or the False Boolean value (if the user clicks Cancel).
Item: Prompt:=PromptString

The Prompt parameter of the Application.InputBox method is a string displayed as the message in the input box. Prompt is a required parameter.

You generally specify PromptString as a string expression.

You can also specify PromptString as a number, a date or a Boolean. In such cases, Excel coerces the number, date or Boolean to a string.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Lines #2, #6 and #8: If (TypeName(InputBoxCancelVariable) = “Boolean”) And (InputBoxCancelVariable = “False”) Then | Else | End If

Item: If… Then… Else… End If

The If… Then… Else statement conditionally executes a group of statements (StatementsIfCancel, StatementsIfNoInput or StatementsIfInputAndOK) depending on the value of an expression (((TypeName(InputBoxCancelVariable) = “Boolean”) And (InputBoxCancelVariable = “False”)) or InputBoxCancelVariable = “”).

Item: TypeName(InputBoxCancelVariable) = “Boolean” And InputBoxCancelVariable = “False”

The condition of the If… Then… Else statement is an expression returning True or False.

The Application.InputBox method returns the False Boolean value when the user clicks Cancel. Therefore, when you check if the user clicks the Cancel button using this macro structure, you test whether 2 conditions are met.

Condition #1: TypeName(InputBoxCancelVariable) = “Boolean”

TypeName(InputBoxCancelVariable) = “Boolean” checks whether InputBoxCancelVariable is a Boolean value.

For these purposes, work with the TypeName function, which returns a string with information about the variable passed as argument (InputBoxCancelVariable). Therefore, TypeName(InputBoxCancelVariable) = “Boolean”:

  • Returns True if InputBoxCancelVariable is a Boolean. This occurs, among others, when the user clicks Cancel.
  • Returns False if InputBoxCancelVariable isn’t a Boolean.

Condition #2: InputBoxCancelVariable = “False”

InputBoxCancelVariable = “False” checks whether InputBoxCancelVariable holds the string “False”. Therefore, InputBoxCancelVariable = “False”:

  • Returns True if InputBoxCancelVariable holds “False”. This occurs, among others, when the user clicks Cancel.
  • Returns False if InputBoxCancelVariable doesn’t hold “False”.

Condition #1 And Condition #2

When you check if the user clicks the Cancel button using this macro structure, both conditions #1 (TypeName(InputBoxCancelVariable) = “Boolean”) and #2 (InputBoxCancelVariable = “False”) must be met.

The And operator performs a logical conjunction. Therefore, the condition of the If… Then… else statement returns True if the user clicks Cancel.

Line #3: StatementsIfCancel

Statements executed if the tested condition ((TypeName(InputBoxCancelVariable) = “Boolean”) And (InputBoxCancelVariable = “False”)) returns True. In other words, these statements are executed if the user clicks Cancel.

Line #4: ElseIf InputBoxCancelVariable = “” Then

Item: ElseIf… Then

The If… Then… Else statement conditionally executes a group of statements (StatementsIfCancel, StatementsIfNoInput or StatementsIfInputAndOK) depending on the value of an expression (((TypeName(InputBoxCancelVariable) = “Boolean”) And (InputBoxCancelVariable = “False”)) or InputBoxCancelVariable = “”).

Item: InputBoxCancelVariable = “”

The condition-n of the If… Then… Else statement is an expression returning True or False.

You can check if the user didn’t enter any input prior to clicking OK by testing whether InputBoxCancelVariable holds a zero-length string (“”). In other words, if the user doesn’t enter any input and clicks the OK button, InputBoxCancelVariable = 0 returns True.

Line #5: StatementsIfNoInput

Statements executed if the tested condition (InputBoxCancelVariable = “”) returns True. In other words, these statements are executed if the user doesn’t enter any input and clicks the OK button.

Line #7: StatementsIfInputAndOK

Statements executed if none of the tested conditions (((TypeName(InputBoxCancelVariable) = “Boolean”) And (InputBoxCancelVariable = “False”)) or InputBoxCancelVariable = “”) return True. In other words, these statements are executed if the user enters an input and clicks the OK button.

Macro example to create InputBox and check if user clicks Cancel button with Application.InputBox method

The following macro example:

  1. Creates an input box with the Application.InputBox method.
  2. Assigns the value returned by the Application.InputBox method to a variable (myInputBoxCancelVariable = Application.inputBox(…)).
  3. Checks whether user clicked Cancel ((TypeName(myInputBoxCancelVariable) = “Boolean”) And (myInputBoxCancelVariable = “False”)). If the user clicked Cancel, displays a message box confirming this.
  4. If the user didn’t click Cancel, checks whether the user entered no input prior to clicking OK (myInputBoxCancelVariable = “”). If the user entered no input prior to clicking OK, displays a message box confirming this.
  5. If the user entered input and clicked OK, displays a message box with the value held by the variable.
Sub CreateInputBoxMethodCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates an input box with the Application.InputBox method, and (2) handles case where user clicks Cancel button
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare variable to hold value returned by InputBox
    Dim myInputBoxCancelVariable As Variant

    '(1) create InputBox, and (2) assign value returned by Application.InputBox method to variable
    myInputBoxCancelVariable = Application.inputBox(Prompt:="Create Excel VBA InputBox and work with Cancel button")

    'check if user clicked Cancel button and, if appropriate, execute statements
    If (TypeName(myInputBoxCancelVariable) = "Boolean") And (myInputBoxCancelVariable = "False") Then

        'display message box confirming that user clicked Cancel button
        MsgBox "You clicked the Cancel button"

    'check if user entered no input and, if appropriate, execute statements
    ElseIf myInputBoxCancelVariable = "" Then

        'display message box confirming that user entered no input
        MsgBox "You didn't enter an input"

    'if user didn't click Cancel button and entered input, execute statements
    Else

        'display message box with value held by variable
        MsgBox "Your input was: " & myInputBoxCancelVariable

    End If

End Sub

Effects of executing macro example to create InputBox and check if user clicks Cancel button with Application.InputBox method

The following GIF illustrates the results of executing the macro example. As expected:

  • Excel displays an input box created with the Application.InputBox function.
  • The macro identifies whether the user:
    • Clicks the Cancel button;
    • Enters no input prior to clicking OK; or
    • Enters input and clicks OK.
  • Excel displays the appropriate message box depending on the actions taken by the user.

VBA creates input box and checks if user clicks Cancel with Application.InputBox

#9: Create InputBox and check if user clicks Cancel button when working with cell range and Application.InputBox method

VBA code to create InputBox and check if user clicks Cancel button when working with cell range and Application.InputBox method

To create an InputBox that works with a cell range using the VBA Application.InputBox method and check if the user clicks Cancel, use a macro with the following statement structure:

Dim InputBoxRangeCancelVariable As Range
On Error Resume Next
Set InputBoxRangeCancelVariable = Application.InputBox(Prompt:=PromptString, Type:=8)
On Error GoTo 0
If InputBoxRangeCancelVariable Is Nothing Then
    StatementsIfCancel
Else
    StatementsIfRangeInput
End If

Process to create InputBox and check if user clicks Cancel button when working with cell range and Application.InputBox method

To create an InputBox that works with a cell range using the VBA Application.InputBox method and check if the user clicks Cancel, follow these steps:

  1. Explicitly declare an object variable to hold a reference to the Range object representing the cell range (Dim InputBoxRangeCancelVariable As Range).
  2. Enable error-handling with the On Error Resume Next statement.
  3. Create an input box with the Application.InputBox method (Application.InputBox(…)).
  4. Set the Type parameter of the Application.InputBox method to 8 (Type:=8), which results in Application.InputBox returning a Range object.
  5. Assign the value returned by the Application.InputBox method to the object variable (InputBoxRangeCancelVariable = Application.InputBox(…)).
  6. Disable error-handling withe the On Error GoTo 0 statement.
  7. Use an If… Then… Else statement for the following:
    • Testing whether the user clicked Cancel (InputBoxRangeCancelVariable Is Nothing).
    • Executing the appropriate group of statements depending on whether the user clicked Cancel (StatementsIfCancel) or not (StatementsIfRangeInput).

VBA statement explanation

Line #1: Dim InputBoxRangeCancelVariable As Range

The Dim statement declares the InputBoxRangeCancelVariable object variable as of the Range object data type and allocates storage space.

When you check if the user clicks the Cancel button while working with a cell range using this macro structure, you explicitly declare the object variable that holds the reference to the cell range returned by the Application.InputBox method.

Line #2: On Error Resume Next

The On Error Resume Next statement enables an error-handling routine and specifies that, when a run-time error occurs, control goes to the statement following that where the error occurred.

When you check if the user clicks the Cancel button while working with a cell range using this macro structure, On Error Resume Next handles the error caused by line #3 (Set InputBoxRangeCancelVariable = Application.InputBox(Prompt:=PromptString, Type:=8)) if the user clicks Cancel. This error is usually run-time error 424 (object required).

If you don’t declare the InputBoxRangeCancelVariable object variable explicitly, the behavior of the macro and the error caused when the user clicks Cancel usually differs from what I describe in this VBA Tutorial.

Line #3: Set InputBoxRangeCancelVariable = Application.InputBox(Prompt:=PromptString, Type:=8)

Item: Set… =…

The Set statement assigns the object reference returned by the Application.InputBox method (Application.InputBox(…)) to InputBoxRangeCancelVariable.

Item: InputBoxRangeCancelVariable

InputBoxRangeCancelVariable is the object variable you want to hold the Range object returned by the Application.InputBox method.

When working with a cell range and the Application.InputBox method, Application.InputBox usually returns a Range object, unless the user clicks on the Cancel button. The cases where the user clicks on the Cancel button are handled by the On Error Resume Next statement.

Therefore, if you explicitly declare InputBoxRangeCancelVariable when working with this macro structure, you can usually declare it as of the Range object data type.

Item: Application.InputBox(…)

The Application.InputBox method:

  1. Displays an input box;
  2. Waits for the user to either (i) input information and click the OK button (or press the Enter key), or (ii) click the Cancel button (or press the Esc key); and
  3. Returns the information entered in the dialog box (if the user clicks OK or presses Enter).
Item: Prompt:=PromptString

The Prompt parameter of the Application.InputBox method is a string displayed as the message in the input box. Prompt is a required parameter.

You generally specify PromptString as a string expression.

You can also specify PromptString as a number, a date or a Boolean. In such cases, Excel coerces the number, date or Boolean to a string.

PromptString can be composed of multiple lines. To create an input box with multiple lines, please refer to the appropriate section of this Tutorial.

Item: Type:=8

The Type parameter of the Application.InputBox method specifies the data type returned.

When working with a cell range, set Type to 8. In such case, Application.InputBox returns a Range object.

Line #4: On Error GoTo 0

The On Error GoTo 0 statement disables the error-handler enabled in line #2.

Lines #5, #7 and #9: If InputBoxRangeCancelVariable Is Nothing Then | Else | End If

Item: If… Then… Else… End If

The If… Then… Else statement conditionally executes a group of statements (StatementsIfCancel or StatementsIfRangeInput) depending on the value of an expression (InputBoxRangeCancelVariable Is Nothing).

Item: InputBoxRangeCancelVariable Is Nothing

The condition of the If… Then… Else statement is an expression returning True or False.

The Is operator compares InputBoxRangeCancelVariable and Nothing. This expression returns True if both refer to the same.

Nothing is the default value for an object variable. Therefore, if the user clicks Cancel, InputBoxRangeCancelVariable Is Nothing returns True.

Line #6: StatementsIfCancel

Statements executed if the tested condition (InputBoxRangeCancelVariable Is Nothing) returns True. In other words, these statements are executed if the user clicks Cancel.

Line #8: StatementsIfRangeInput

Statements executed if the tested condition (InputBoxRangeCancelVariable Is Nothing) returns False. In other words, these statements are executed if the user enters/selects a cell range as input.

Macro example to create InputBox and check if user clicks Cancel button when working with cell range and Application.InputBox method

The following macro example:

  1. Enables error-handling (On Error Resume Next).
  2. Creates an input box that returns a Range object (Type:=8) with the Application.InputBox method.
  3. Assigns the object reference returned by the Application.InputBox method to an object variable (Set myInputBoxRangeCancelVariable = Application.inputBox(…)).
  4. Disables error-handling (On Error GoTo 0).
  5. Checks whether user clicked Cancel (myInputBoxRangeCancelVariable Is Nothing).
    • If the user clicked Cancel, displays a message box confirming this.
    • If the user didn’t click Cancel, displays a message box with the range reference of the cell range represented by the variable (myInputBoxRangeCancelVariable.Address).
Sub CreateInputBoxMethodCellRangeCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates an input box that works with cell ranges using the Application.InputBox method, and (2) handles case where user clicks Cancel button
    'for further information: https://powerspreadsheets.com/excel-vba-inputbox/

    'declare object variable to hold reference to Range object (cell range) returned by InputBox
    Dim myInputBoxRangeCancelVariable As Range

    'enable error-handling
    On Error Resume Next

    '(1) create InputBox that works with cell range, and (2) assign value returned by Application.InputBox method to variable
    Set myInputBoxRangeCancelVariable = Application.inputBox(Prompt:="Create Excel VBA InputBox that works with cell range and handles Cancel button", Type:=8)

    'disable error-handling
    On Error GoTo 0

    'check if user clicked Cancel button and, if appropriate, execute statements
    If myInputBoxRangeCancelVariable Is Nothing Then

        'display message box confirming that user clicked Cancel button
        MsgBox "You clicked the Cancel button"

    'if user didn't click Cancel button, execute statements
    Else

        'display message box with address of cell range represented by object variable
        MsgBox "Your input was: " & myInputBoxRangeCancelVariable.Address

    End If

End Sub

Effects of executing macro example to create InputBox and check if user clicks Cancel button when working with cell range and Application.InputBox method

The following GIF illustrates the results of executing the macro example. As expected:

  • Excel displays an input box created with the Application.InputBox function. The InputBox allows the user to select a cell range.
  • The macro identifies whether the user:
    • Clicks the Cancel button; or
    • Selects or otherwise enters an appropriate cell range.
  • Excel displays the appropriate message box depending on the actions taken by the user.

VBA creates input box that works with cell range and checks if user clicks Cancel

Понравилась статья? Поделить с друзьями:
  • Excel vba введите число
  • Excel vba в книге с общим доступом
  • Excel vba ближайшее значение
  • Excel vba без заливки
  • Excel vba ассоциативные массивы