Excel vba введите число

Использование метода Application.InputBox в VBA Excel, его синтаксис и параметры. Значения, возвращаемые диалогом Application.InputBox. Примеры использования.

Метод Application.InputBox предназначен в VBA Excel для вывода диалогового окна с более расширенными возможностями, чем диалоговое окно, отображаемое функцией InputBox. Главным преимуществом метода Application.InputBox является возможность автоматической записи в поле ввода диапазона ячеек (в том числе одной ячейки) путем его выделения на рабочем листе книги Excel и возвращения различных данных, связанных с ним, а также проверка соответствия возвращаемого значения заданному типу данных.

Синтаксис метода

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

Обязательным параметром метода Application.InputBox является Prompt, если значения остальных параметров явно не указаны, используются их значения по умолчанию.

Обратите внимание на то, что

  • оператор InputBox вызывает функцию InputBox, а
  • оператор Application.InputBox вызывает метод InputBox.

Чтобы не было путаницы, метод InputBox пишут как метод Application.InputBox, в том числе и в справке разработчика.

Параметры метода

Параметр Описание Значение по умолчанию
Prompt Обязательный параметр. Выражение типа String, отображаемое в диалоговом окне в виде сообщения, приглашающего ввести данные в поле. Разделить на строки сообщение можно с помощью константы vbNewLine. Нет
Title Необязательный параметр. Выражение типа Variant, отображаемое в заголовке диалогового окна. Слово «Ввод»
Default Необязательный параметр. Выражение типа Variant, отображаемое в поле ввода при открытии диалога.  Пустая строка
Left Необязательный параметр. Выражение типа Variant, определяющее в пунктах расстояние от левого края экрана до левого края диалогового окна (координата X).* Горизонтальное выравнивание по центру**
Top Необязательный параметр. Выражение типа Variant, определяющее в пунктах расстояние от верхнего края экрана до верхнего края диалогового окна (координата Y).* Приблизительно равно 1/3 высоты экрана***
HelpFile Необязательный параметр. Выражение типа Variant, указывающее имя файла справки для этого поля ввода. Нет****
HelpContextID Необязательный параметр. Выражение типа Variant, указывающее идентификатор контекста в справочном разделе файла справки. Нет****
Type Необязательный параметр. Выражение типа Variant, указывающее тип возвращаемых данных. 2 (текст)

* Параметры Left и Top учитываются при отображении диалогового окна методом Application.InputBox в Excel 2003, а в последующих версиях Excel 2007-2016 уже не работают.
**При первом запуске горизонтальное выравнивание устанавливается по центру, при последующих — форма отобразиться в том месте, где ее последний раз закрыли.
***При первом запуске вертикальное расположение приблизительно равно 1/3 высоты экрана, при последующих — форма отобразиться в том месте, где ее последний раз закрыли.
**** Если будут указаны параметры HelpFile и HelpContextID, в диалоговом окне появится кнопка справки.

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

Диалоговое окно, созданное методом Application.InputBox, возвращает значение типа Variant и проверяет соответствие возвращаемого значения типу данных, заданному параметром Type. Напомню, что тип значений Variant является универсальным контейнером для значений других типов, а в нашем случае для возвращаемых в зависимости от значения параметра Type.

Аргументы параметра Type и соответствующие им типы возвращаемых значений:

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

Примеры

В отличие от других встроенных диалоговых окон VBA Excel, Application.InputBox при запуске процедуры непосредственно из редактора, открывается прямо в редакторе, и, чтобы выбрать диапазон ячеек на рабочем листе, нужно по вкладке браузера перейти в книгу Excel. Поэтому для тестирования диалога Application.InputBox удобнее создать кнопку, перетащив ее на вкладке «Разработчик» из «Элементов управления формы» (не из «Элементов ActiveX») и в окошке «Назначить макрос объекту» выбрать имя тестируемой процедуры. Чтобы можно было выбрать процедуру сразу при создании кнопки, она должна быть уже вставлена в стандартный программный модуль. Можно назначить процедуру кнопке позже, кликнув по ней правой кнопкой мыши и выбрав в контекстном меню «Назначить макрос…».

Пример 1 — параметры по умолчанию

Тестируем метод Application.InputBox с необязательными параметрами по умолчанию. Аргумент параметра Type по умолчанию равен 2.

Sub Test1()

Dim a As Variant

a = Application.InputBox(«Выберите ячейку:»)

MsgBox a

End Sub

Скопируйте код и вставьте в стандартный модуль, для удобства создайте на рабочем листе кнопку из панели «Элементы управления формы» и назначьте ей макрос «Test1». На рабочем листе заполните некоторые ячейки разными данными, нажимайте кнопку, выбирайте ячейки и смотрите возвращаемые значения.

Клик по кнопке «OK» диалога Application.InputBox в этом примере возвращает содержимое выбранной ячейки (или левой верхней ячейки выбранного диапазона), преобразованное в текстовый формат. У дат в текстовый формат преобразуется их числовое представление.

Клик по кнопке «Отмена» или по закрывающему крестику возвращает строку «False».

Пример 2 — возвращение объекта Range

В этом примере тестируем метод Application.InputBox с обязательным параметром Prompt, разделенным на две строки, параметром Title и значением параметра Type равным 8. Так как в данном случае диалог в качестве значения возвращает объект Range, он присваивается переменной с помощью оператора Set. Для этого примера создайте новую кнопку из панели «Элементы управления формы» и назначьте ей макрос «Test2».

Sub Test2()

Dim a As Variant

Set a = Application.InputBox(«Пожалуйста,» _

& vbNewLine & «выберите диапазон:», _

«Наш диалог», , , , , , 8)

MsgBox a.Cells(1)

MsgBox a.Address

End Sub

В первом информационном окне MsgBox выводится значение первой ячейки выбранного диапазона, во втором — адрес диапазона.

Напомню, что обращаться к ячейке в переменной диапазона «a» можно не только по порядковому номеру (индексу) самой ячейки, но и по индексу строки и столбца, на пересечении которых она находится. Например, оба выражения

указывают на первую ячейку диапазона. А в объектной переменной «a» с присвоенным диапазоном размерностью 3х3 оба выражения

указывают на центральную ячейку диапазона.

При использовании метода Application.InputBox происходит проверка введенных данных: попробуйте понажимать кнопку «OK» с пустым полем ввода и с любым введенным текстом (кроме абсолютного адреса). Реакция в этих случаях разная, но понятная.

Есть и отрицательные моменты: при использовании в диалоге Application.InputBox параметра Type со значением равным 8, нажатие кнопок «Отмена» и закрывающего крестика вызывают ошибку Type mismatch (Несоответствие типов). Попробуйте нажать кнопку «Отмена» или закрыть форму диалога.

Решить эту проблему можно, добавив обработчик ошибок. Скопируйте в стандартный модуль код следующей процедуры, создайте еще одну кнопку и назначьте ей макрос «Test3».

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

Sub Test3()

Dim a As Variant

‘При возникновении ошибки

‘перейти к метке «Inform»

On Error GoTo Inform

Set a = Application.InputBox(«Пожалуйста,» _

& vbNewLine & «Выберите диапазон:», _

«Наш диалог», , , , , , 8)

MsgBox a.Cells(1)

MsgBox a.Address

‘Выйти из процедуры,

‘если не произошла ошибка

Exit Sub

‘Метка

Inform:

‘Вывести информационное окно с

‘сообщением об ошибке

MsgBox «Диалог закрыт или нажата кнопка « _

& Chr(34) & «Отмена» & Chr(34) & «!»

End Sub

Попробуйте теперь нажать кнопку «Отмена» или закрыть форму диалога крестиком.

Пример 3 — возвращение массива

Скопируйте в стандартный модуль код процедуры ниже, создайте четвертую кнопку и назначьте ей макрос «Test4». В этой процедуре указан только аргумент параметра Type равным 64, остальные необязательные параметры оставлены по умолчанию.

Sub Test4()

Dim a As Variant

a = Application.InputBox(«Выберите диапазон:», , , , , , , 64)

MsgBox a(3, 3)

End Sub

Откройте диалоговую форму, нажав четвертую кнопку, и выберите диапазон размерностью не менее 3х3. Нажмите «OK»: информационное сообщение выведет значение соответствующего элемента массива «a», в нашем случае — «a(3, 3)». Если вы выберите диапазон по одному из измерений меньше 3, тогда строка «MsgBox a(3, 3)» вызовет ошибку, так как указанный элемент выходит за границы массива. Эта же строка по этой же причине вызовет ошибку при нажатии кнопки «Отмена» и при закрытии диалога крестиком. Если закомментировать строку «MsgBox a(3, 3)», то закрываться диалог будет без ошибок и при нажатии кнопки «Отмена», и при закрытии диалога крестиком.

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

Sub Test5()

Dim a As Variant

a = Application.InputBox(«Выберите диапазон:», , , , , , , 64)

MsgBox «Максимальный индекс 1 измерения = « & UBound(a, 1) & _

vbNewLine & «Максимальный индекс 2 измерения = « & UBound(a, 2)

End Sub

только присваивайте значения выражений «UBound(a, 1)» и «UBound(a, 2)» числовым переменным. А этот код используйте для ознакомления с работой функции UBound и ее тестирования.

В этой процедуре ошибка выдается при выборе одной ячейки или диапазона в одной строке, очевидно, Excel воспринимает его как одномерный массив. Хотя при выборе диапазона в одном столбце, по крайней мере в Excel 2016, все проходит гладко и вторая строка информационного сообщения отображается как «Максимальный индекс 2 измерения = 1».

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

Пример 4 — возвращение формулы

Возвращение формулы рассмотрим на следующем примере:

Sub Test6()

Dim a As Variant

a = Application.InputBox(«Создайте формулу:», , , , , , , 0)

Cells(1, 1) = a

End Sub

На активном листе Excel заполните некоторые ячейки числами и запустите процедуру на выполнение. После отображения диалога Application.InputBox выбирайте по одной ячейке с числами, вставляя между ними математические операторы. После нажатия на кнопку «OK» формула запишется в первую ячейку активного рабочего листа «Cells(1, 1)» (в текст формулы ее не выбирайте, чтобы не возникла циклическая ссылка). При нажатии на кнопку «Отмена» и при закрытии диалога крестиком в эту ячейку запишется слово «Ложь».

Можно записывать не только математические формулы, но и объединять содержимое ячеек с помощью оператора «&» и многое другое. Только не понятно, для чего это вообще нужно, как, впрочем, и возврат логических, числовых значений и значений ошибки. Вы можете протестировать их возврат с помощью процедуры «Test6», заменив в ней параметр Type метода Application.InputBox соответствующим для возвращения логических, числовых значений и значений ошибки.

Подобно многим языкам программирования Visual Basic for Application (VBA) позволяет создать три типа процедур: Sub, Function, Property.

Процедура – это набор описаний и инструкций, сгруппированных для выполнения.

Процедура Sub – набор команд, с помощью которого можно решить определенную задачу. При ее запуске выполняются команды процедуры, а затем управление передается в приложение или процедуру, которая вызвала процедуру Sub. Записываемые макросы автоматически описываются как процедуры Sub, любой макрос или другой код VBA, который просто выполняет определенный набор действий, используя приложения Office, и обычно является процедурой Sub.

Процедура Function (или функция) также представляет собой набор команд, который решает определенную задачу. Различия заключается в том, что процедуры данного типа обязательно возвращают значение. При создании процедуры Function можно описать тип данных, который возвращает функция. Функции обычно используются при выполнении вычислений, операциями с текстом, либо возвращают логические значения.

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

Структура процедуры

При записи процедуры требуется соблюдать правила ее описания. Упрощенный синтаксис для процедур Sub является следующим:

Sub имя ([аргументы])
Инструкции
End Sub

Синтаксис описания функций очень похож на синтаксис описания процедуры Sub, однако, имеются некоторые отличия:

Function имя ([аргументы]) [As Тип]
Инструкции
имя = выражение
End Function

Использование операторов

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

Объявления

Объявление – это оператор, сообщающий компилятору VBA о намерениях по по­воду использования в программе именованного объекта (переменной, константы, поль­зовательского типа данных или процедуры). Кроме того, объявление задает тип объекта и обеспечивает компилятору дополнительную информацию о том, как ис­поль­зовать данный объект. Объявив объект, можно использовать его в любом месте программы.

Переменные – это именованные значения, которые могут изменяться во время выполнения программы.

Рассмотрим пример объявления переменной.

С помощью оператора Dim объявляется переменная с именем МоеЛюбимоеЧисло и объявляется, что значение, которое она будет содержать, должно быть целым:

Dim МоеЛюбимоеЧисло As Integer

Константы представляют собой именованные значения, которые не меняются.

Оператор Constant создает строковую константу (текст) с именем НеизменныйТекст, представляющую собой набор символов Вечность:

Constant НеизменныйТекст = "Вечность"

Оператором Type объявляется пользовательский тип данных с именем Самоделкин, определяя его как структуру, включающую строковую переменную с именем Имя и переменную типа Date с именем ДеньРождения. В данном случае объявление займет несколько строк:

Type Самоделкин
Имя As String
ДеньРождения As Date
End Type

Объявление Private создает процедуру типа Sub с именем СкрытаяПроцедура, говоря о том, что эта процедура является локальной в смысле об­ласти видимости. Завершающий процедуру оператор End Sub считается частью объ­явления.

Private Sub СкрытаяПроцедура ()
инструкции
End Sub

Оператор присваивания

Оператор присваивания = приписывают переменным или свойствам объектов конкретные значения. Такой оператор всегда состоят из трех частей: имени переменной, или свойства, знака равенства и выражения, задающего нужное значение.

Оператор = присваивает переменной МоеЛюбимоеЧисло значение суммы переменной ДругоеЧисло и числа 12.

МоеЛюбимоеЧисло = ДругоеЧисло + 12

В следующей строке кода, записывается, что свойству Color (Цвет) объекта AGraphicShape присваивается значение Blue (Синий) в предположении, что Blue является именованной константой:

AGraphicShape.Color = Blue

В следующеей строке, чтобы задать значение переменной КвадратныйКорень, для текущего значения переменной МоеЛюбимоеЧисло вызывается функция Sqr — встроенная функция VBA вычисления квадратного корня:

КвадратныйКорень = Sqr (МоеЛюбимоеЧисло)

В VBA выражением называется любой фрагмент программного кода, задающий некоторое числовое значение, строку текста или объект. Выражение может содержать любую комбинацию чисел или символов, констант, переменных, свойств объектов, встроенных функций и процедур типа Function, связанных между собой знаками операции (например, + или *). Несколько примеров выражений:

Выражение

Значение

3.14

3.14

Xn*5

10 (в предположении, что Xn = 2)

(12 — Sqr(x))/5

2 (в предположении, что х = 4)

«Розы красные,» &
« фиалки фиолетовые»

Розы красные, фиалки фиолетовые

Выполняемые операторы

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

  • вызов процедуры;
  • активизация метода некоторого объекта;
  • управление порядком, в котором должны выполняться другие операторы, посредством организации циклов или выбором участка программного кода (из нескольких альтернатив) для последующего выполнения;
  • выполнение одного из встроенных операторов VBA или функции.

Пример. Оператор, вызывающий для выполнения метод Rotate объекта AGraphicShape:

AGraphicShape. Rotate(90)

Запись нескольких операторов

Как правило, каждый оператор занимает одну строку программного кода, но VBA не обязывает уместить оператор в одной строке. Если оператор слишком длинный, можно разместить его в двух или более строках, добавив в конце каждой из строк (кроме последней) символ подчеркивания (_).

Можно сделать и наоборот — разместить несколько операторов в одной строке программного кода. Например,

Dim A As Integer, В As Integer: A = 3: B = 5: A = A +B

Эта строка программного кода эквивалентна следующим четырем строкам:

Dim A As Integer, В As Integer
A = 3
B = 5
А = А + В

Самыми простыми диалоговыми окнами являются окна сообщений (message boxes) — это диалоговые окна, которые выдают пользователю сообщения и снабжаются одной или более кнопками для выбора. В VBA они создаются с использованием функции MsgBox.

В своей самой простой форме MsgBox используется как оператор с одним аргументом – сообщением, которое должно отображаться. Например, приведенный ниже макрос создаёт сообщение, показанное на рисунке.

Sub Program ()
MsgBox "Это - окно сообщений"
End Sub

Статья 3 - Картинка 1

MsgBox можно использовать для отображения числового значения.

Sub ShoeValue()
Amount = 10
MsgBox Amount
End Sub

Статья 3 - Картинка 2

Переменной Amount присваивается значение 10. На следующей строке для отображения значения Amount используется MsgBox. Вокруг Amount нет кавычек, поскольку это – значение переменной, которое нужно выдать на экран, а не слово «Amount».

Чтобы использовать вместе две отдельные строки в одном окне сообщения, следует использовать операцию конкатенации (&) — объединение.

Sub SayGoodNight()
Name = "Саша"
MsgBox "Пожелайте доброй ночи " & Name
End Sub

Статья 3 - Картинка 3

Переменной Name присваивается строка «Саша». В строке кода с MsgBox задаётся текстовая строка «Пожелайте доброй ночи «, за которой следует & Name, указывая MsgBox присоединить значение переменной Name к предыдущей текстовой строке.

Опции MsgBox

Статья 3 - Картинка 4

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

MsgBox "Это - замечательное окно сообщений", _vbExclamation, "Персональное окно"

Статья 3 - Картинка 4

Существует четыре значка для окон сообщений. Каждый имеет определённое числовое значение, которое должно передаваться в качестве аргумента MsgBox. Однако вместо числа можно использовать константы со специальными именами, встроенные в VBA.

Таблица 1

Значки окна сообщений MsgBox

Отображение

Константа

Когда используется

Image4.gif

vbInformation

для сообщения, не требующего ответа

Image5.gif

vbQuestion

для того, чтобы задать вопрос

Image6.gif

vbExclamation

для выдачи важной информации

Image7.gif

vbCritical

для предупреждения

MsgBox как функция

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

Статья 3 - Картинка 6

После выбора соответствующей кнопки Excel получает информацию о том, какую кнопку выбрали.

Общий формат для функции MsgBox:

MsgBox(prompt [, buttons] [, title])

где prompt — единственный обязательный аргумент. Для окна сообщений следует задавать текстовую строку с информацией. если вы хотите изменить заголовок, появляющийся в верхней части окна, задайте для заголовка (title) текстовую строку. По умолчанию используется заголовок Microsoft Excel.

Таблица 2 Комбинации кнопок MsgBox

Отображение

Константа

Когда используется

Image9.gif

vbOKOnly

Когда не требуется от пользователя принятия решения

Image9.gifImage11.gif

vbOKCancel

Когда окно сообщений объясняет возможное действие. Позволяет пользователю сделать выбор с помощью кнопки Отмена

Image9.gifImage10.gif

vbYesNo

Альтернатива константе vbOKCancel, когда кажется, что это сделает окно сообщений более понятным

Image9.gifImage11.gifImage10.gif

vbYesNoCancel

Для таких ситуаций, как выход или закрытие файлов без сохранения (подобно ситуации, показанной на рисунке выше)

Image12.gifImage13.gifImage14.gif

vbAbortRetryIgnore

При ответе на сообщения об ошибках диска или файла

Image13.gifImage11.gif

vbRetryCancel

При ответе на сообщения об ошибках диска или файла

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

Примеры решения задач

Приведем несколько примеров решения задач на VBA.

Пример 1. Вычислить значение выражения a равного

Статья 3 - Картинка 7, при x = 3, y = 2.5

Решение.

Sub выражение1()
Dim A, x, y
 
x = 3
y = 2.5
 
A = 2 * x - 3 * y
 
MsgBox (A)
 
End Sub

Пояснение решения.

В строке Dim A, x, y объявляются переменные A, x, y.

Пример 2.

Пример 2. Вычислить значение выражения a равного

Статья 3 - Картинка 7, при x = 3, y = 2.5

Замечание: значения x и y вводит пользователь.

Решение.

Sub выражение2()
Dim A, x, y As Double
 
x = InputBox("Введите x=")
y = InputBox("Введите y=")
 
A = 2 * x - 3 * y
 
MsgBox (A)
 
End Sub

Пояснение решения.

В строке Dim A, x, y As Double описываются переменные A, x, y как числа двойной точности.

При использовании строки

x = InputBox("Введите x=")

появиться окно

Статья 3 - Картинка 9

Пример 3

Пример 3. Вычислить значение выражения a равного

Статья 3 - Картинка 7, при x = 3, y = 2.5

Замечание: значения x и y вводит пользователь, ответ выводится в виде «a = <значение>».

Решение.

Sub выражение3()
Dim A, x, y As Double
Dim ответ As String
 
x = InputBox("Введите x=")
y = InputBox("Введите y=")
 
A = 2 * x - 3 * y
ответ = "a=" + Str(A)
 
MsgBox (ответ)
 
End Sub

Пояснение решения.

В строке Dim ответ As String описывается переменная ответ как строковая.

Код Str(A) преобразует значение переменной A в строку.

Пример 4

Пример 4. Вычислить значения выражений при x = 3, y = 2.5

Статья 3 - Картинка 7,

Статья 3 - Картинка 12,

Статья 3 - Картинка 13,

Статья 3 - Картинка 14,

Статья 3 - Картинка 15

Решение.

Sub выражение4()
Dim A, b, c, d, a1, x, y As Double
 
x = InputBox("Введите x=")
y = InputBox("Введите y=")
 
A = 2 * x - 3 * y
b = (2 * x - 3 * y) / 2
c = (2 * x - 3 * y) / 2 * x
d = (2 * x - 3 * y) / (2 * x)
a1 = (2 * x - 3 * y) / (2 * x) + (5 - x) / (3 + y)
 
MsgBox ("a=" + Str(A))
MsgBox ("b=" + Str(b))
MsgBox ("c=" + Str(c))
MsgBox ("d=" + Str(d))
MsgBox ("a1=" + Str(a1))
 
End Sub

Пример 5

Пример 5. Выполнить пример 4, другим способом, с помощью вспомогательных переменных.

Решение.

Sub выражение5()
Dim A, b, c, d, a1, a2, b1, c1, c2, x, y As Double
 
x = InputBox("Введите x=")
y = InputBox("Введите y=")
 
A = 2 * x - 3 * y
b = (2 * x - 3 * y) / 2
c = (2 * x - 3 * y) / 2 * x
d = (2 * x - 3 * y) / (2 * x)
a1 = (2 * x - 3 * y) / (2 * x) + (5 - x) / (3 + y)
 
‘ новое решение
b1 = A / 2
c1 = b * x
c2 = b / (2 * x)
a2 = d + (5 - x) / (3 + y)
MsgBox ("a=" + Str(A))
MsgBox ("b=" + Str(b))
MsgBox ("c=" + Str(c))
MsgBox ("d=" + Str(d))
MsgBox ("a1=" + Str(a1))
MsgBox ("b1=" + Str(b1))
MsgBox ("c1=" + Str(c1))
MsgBox ("c2=" + Str(c2))
MsgBox ("a2=" + Str(a2))
 
End Sub

Пример 6

Пример 6. Вычислить площадь треугольника по трем известным сторонам. Например, a = 3, b = 4, c = 5.

Решение.

Sub Герон1()
Dim A, b, c, p, s As Double
A = 3
b = 4
c = 5
 
p = (A + b + c) / 2
s = Sqr(p * (p - A) * (p - b) * (p - c))
 
MsgBox ("s=" + Str(s))
 
End Sub

Пояснение решения.

Для решения задачи используется формула Герона.

Пример 7

Пример 7. Вычислить площадь треугольника по трем известным сторонам.

Решение.

Sub Герон2()
Dim A, b, c, p, s As Double
 
A = Val(InputBox("Введите a="))
b = Val(InputBox("Введите b="))
c = Val(InputBox("Введите c="))
 
p = (A + b + c) / 2
s = Sqr(p * (p - A) * (p - b) * (p - c))
 
MsgBox ("s=" + Str(s))
 
End Sub

Пояснение решения.

Код Val(InputBox(«Введите a=»)) преобразует введенное значение через InputBox в число, так как InputBox возвращает строку. Если такого преобразования не сделать, то программа правильно вычислять s не будет.

Пример 8

Пример 8. Вычислить гипотенузу прямоугольного треугольника по двум катетам.

Решение.

Sub гипотенуза()
Dim a, b, c, p, s As Double
 
a = Val(InputBox("Введите a="))
b = Val(InputBox("Введите b="))
 
c = Sqr(a ^ 2 + b ^ 2)
 
MsgBox ("c=" + Str(c))
 
End Sub

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

The VBA Application.InputBox provides a dialog for you to get a response from the user.

You can specify the response type from the user. These include numbers, string, date and a range.

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

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

    Dim name As String
    name = Application.InputBox("Please enter your name")
    
    Debug.Print name

End Sub

inputbox

Important

Confusingly there are two InputBoxes in Excel VBA.

  1. Application.InputBox
  2. InputBox(also calledVBA.InputBox)

They are almost the same except that:

  1. Application.InputBox allows you to specify the variable type of result e.g. String, integer, date, range.
  2. The Application.InputBox parameters Left and Top are not used by VBA.

In, the example below, the Application.InputBox allows you to specify the type but the VBA.InputBox doesn’t:

number = VBA.InputBox("Enter Number")

number = Application.InputBox("Enter number", Type:=1) ' The type is number 

In this article, we will be dealing primarily with the Application.InputBox.

InputBox Syntax

InputBox Prompt, Title, default , Left, Top, Helpfile, Helpfilecontextid, Type

Note that Prompt is the only parameter that is required. The others are optional. See the next section for more info.

InputBox Parameters

Prompt – this is the text displayed by the InputBox e.g. “Please enter a number between one and ten”, “Please select a range”.

Title[optional] – this is the text that is displayed in the title bar of the InputBox.

Default[optional]– this will be the response if no response is entered by the user.

Left[optional] – not used. If you need to position the InputBox you need to use the VBA.InputBox.

Top[optional] – not used. If you need to position the InputBox you need to use the VBA.InputBox.

Helpfile[optional] – specifies a related help file if your application has one(hint: it probably doesn’t unless it is a legacy application.)

Helpfilecontextidl[optional] – specifies a position in the help file.

Type[optional] – specifies the type of value that will be returned. If this parameter is not used then the return type is text. See below for a list of options for this parameter.

What makes using the InputBox simple is that you really only need to use 4 of these parameters, namely prompt, title, default and type.

VBA Optional Parameters

As, we saw in the above section, VBA has a lot of optional parameters. Sometimes we want to use an optional parameter but don’t need the optional parameters before it. We can deal with this in two ways:

  1. Leave the other optional parameters blank.
  2. Use the name of the parameter.

Here are examples of each method:

' Method 1: Using blank parameters
Number = Application.InputBox("Enter number", , 99)
Number = Application.InputBox("Enter number", , 99, , , , , 1)

' Method 2: Naming the parameters
Number = Application.InputBox("Enter number", Default:=99)
Number = Application.InputBox("Enter number", Default:=99, Type:=Number)

You can see that naming the parameters is a better idea as it makes the code much more readable and understandable.

InputBox Title Parameter

The Title parameter simply allows you to see the Title of the InputBox dialog. The following examples shows this:

Dim year As Long
year = Application.InputBox("Enter the Year", Title:="Customer Report")

vba inputbox title

InputBox Default Parameter

The default value is simply the value that will be returned if the user does not enter a value. This value is displayed in the InputBox when it appears.

When the following code runs,  the value Apple is displayed in the InputBox when it appears:

Dim fruit As Long
fruit = Application.InputBox("Please enter fruit", Default:="Apple")

inputbox default parameter

InputBox Type Parameter Options

Value Type
0 Formula
1 Number
2 String
4 Boolean — True or False
8 Range
16 An error value like #N/A
64 Array of values

You can create your own constants for the Type parameter if you want your code to be more readable:

Public Enum appInputBox
    IBFormula = 0
    IBNumber = 1
    IBString = 2
    IBBoolean = 4
    IBRange = 8
    IBError = 16
    IBArray = 64
End Enum

You can then use them like this:

year = Application.InputBox("Enter the Year", Type:=IBNumber)
year = Application.InputBox("Enter your name", Type:=IBString)

Getting the Range

To get a range from the user we set Type to 8.

If we set the return variable to be a range we must use the Set keyword like in this example:

Dim rg As Range
Set rg = Application.InputBox("Enter the Year", Type:=8)

If you leave out the Set keyword you will get the runtime error 91: “object variable or with block not set”.

In VBA we can declare the variable as a variant in VBA. This means that VBA will set the type at runtime:

' In both cases the variable will be a variant
Dim rg1 As Variant
Dim rg2

If we replace the Set keyword with a variant then the InputBox will return an array of values instead of the range object:

Dim rg As Variant

' Returns an array of values
rg = Application.InputBox("Enter the Year", Type:=8)

' Returns the range object
Set rg = Application.InputBox("Enter the Year", Type:=8)

Cancelling the Range

One problem with selecting the range is that if the user clicks cancel then VBA gives an error.

There is no nice way around this. We have to turn off errors and then check the return value. We can do it like this:

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

    Dim rg As Range
    
    ' Turn off errors
    On Error Resume Next
    
    Set rg = Application.InputBox("Please enter Range", Type:=8)
    
    ' Turn on errors
    On Error Goto 0
    
    ' Display the result
    If rg Is Nothing Then
        MsgBox "The range was cancelled"
    Else
        MsgBox "The selected range is " & rg.Address
    End If

End Sub

Related Reading

VBA Message Box

VBA UserForm – A Guide for Everyone

VBA UserForm Controls – A Guide for Everyone

What’s Next?

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

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

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

Построение диалогов

См. также Экранные формы (Forms).

Диалоги

Диалоги являются абсолютно необходимым средством для повышения управляемости и гибкости макропрограмм.
Они представлены двумя командами: MsgBox (диалог с кнопками) и InputBox (для ввода значений).
Для начинающих программистов этого вполне достаточно.

Синтаксис команд:

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])


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


InputBox

Диалог предназначен для ввода единичного символьного (строкового) значения. Как видно из основного синтаксиса:

InputBox(prompt[, title] [, default] [, xpos] [, ypos]),

обязательным является только поясняющий текст (prompt).

Появляется возможность указать значение по умолчанию (default), пренебрегать которым не стоит.
Ведь во многих случаях оно может быть предсказано и пользователю не придется заниматься утомительным вводом.

Также можно указать в твипсах (1/20 часть пикселя, а не пункта, как принято в полиграфии) координаты окна (xpos, ypos).
Если соответствующие координаты опущены, то диалог центрируется относи­тельно горизонтали и опускается примерно на треть экрана по вертикали.

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

     Dim x As Single
     x = InputBox("Введите значение x для подстановки")

Результат будет выглядеть так:

Если внимательно посмотреть на текст программы, то закономерным будет вопрос: переменной x (числового типа Single) будет передаваться строковое значение, что является ошибочным?

Однако в VBA это будет обработано правильно, если пользователь введет любое число: преобразование пройдет само собой. Если же он введет буквы или нажмёт кнопку отмены (Cancel), то переменной будет присваиваться строковое значение, что породит ошибку:

Избежать подобной ситуации можно двумя способами, предоставляющими различные возможности.

Решение 1

     x = Val(InputBox("Введите значение x для подстановки"))

Здесь сразу происходит преобразование типа возвращаемого значения функцией Val(). В результате при вводе букв они будут:

  1. преобразованы в 0,
  2. если в начале строки введены числа («125xyz»), то строка преобразуется в число (125).

При нажатии на кнопку Cancel будет возвращена пустая строка («»), преобразуемая в 0.

Если такой ввод допустим в принципе, то нет возможности прекратить выполнение программы без дополнительного запроса пользователю.

Решение 2

     Dim x As Single, xVal As String
     xVal = InputBox("Введите значение x для подстановки")
     If xVal = "" Then Exit Sub
     x = Val(xVal)

В данном случае создаётся дополнительная переменная (xVal), в которой хранится результат ввода. Что мы имеем в результате?

  1. В строке, выделенной красным, проведен анализ результата ввода и выход из программы при пустой строке.
    Такой подход вполне приемлем и для случая, когда пользователь забыл задать значение.
    Здесь ему может быть задан вопрос о необходимости прерывания программы.
  2. Значение, сохраненное в xVal, можно использовать и в дальнейшем. В том числе для детальной разборки или анализа, в том числе на предмет правильности ввода.
  3. Появляется возможность ввести несколько значений, например, через запятую, которые потом можно анализировать и использовать в соответствии с замыслом программиста.
  4. Занята дополнительная память, что является платой за функциональность.

InputBox в Excel VBA

К сожалению, объектная модель Word и Excel не совпадают, в связи с чем приходится говорить, что в Excel можно воспользоваться ещё одним способом:

     Dim x As Variant
     x = Application.InputBox(Prompt:="Введите значение x для подстановки", Type:=1)

В этой ситуации пользователь сможет ввести данные только указанного типа (числового). Если можно вводить несколько типов, то следует задать тип как сумму соответствующих типов: 1+2 (либо сразу 3) — можно вводить цифры и символы.

    Перечень типов:

  • 0 = formulas
  • 1 = numbers
  • 2 = strings
  • 4 = logical values
  • 8 = cell references
  • 16 = error values
  • 64 = arrays

MsgBox

Вспомним синтаксис команды:

MsgBox(prompt[, buttons] [, title] [, helpfile, context])

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

Переменная Word Значение Описание
vbOKOnly 0 Вывести только кнопку OK
vbOKCancel 1 Вывести кнопки OK и Cancel
vbAbortRetryIgnore 2 Вывести кнопки Abort, Retry и Ignore
vbYesNoCancel 3 Вывести кнопки Yes, No и Cancel
vbYesNo 4 Вывести кнопки Yes и No
vbRetryCancel 5 Вывести кнопки Retry и Cancel
vbCritical 16 Вывести картинку Critical Message
vbQuestion 32 Вывести картинку Warning Query
vbExclamation 48 Вывести картинку Warning Message
vbInformation 64 Вывести картинку Information Message
vbDefaultButton1 0 По умолчанию активна 1‑я кнопка
vbDefaultButton2 256 По умолчанию активна 2‑я кнопка
vbDefaultButton3 512 По умолчанию активна 3‑я кнопка
vbDefaultButton4 768 По умолчанию активна 4‑я кнопка
vbApplicationModal 0 Диалог модален для Word: для продолжения работы в приложении и самого макроса нужно нажать на одну из кнопок
vbSystemModal 4096 Диалог модален для Windows: все приложения прекращают работу до тех пор, пока пользователь не нажмет на одну из кнопок
vbMsgBoxHelpButton 16384 Добавляет в диалог кнопку Help (Справка)
VbMsgBoxSetForeground 65536 Переводит окно диалога на передний план (практическое применение неизвестно)
vbMsgBoxRight 524288 Надписи выравниваются вправо
vbMsgBoxRtlReading 1048576 Для языков, читаемых справа налево

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

Пример: MsgBox «Значение х достигло » & x

Диалог будет выглядеть так:

Следует отметить, что кнопка ОК обладает интересным свойством: её можно нажать как мышкой, так и клавишами Enter, Space и Esc.

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

Ниже приведен список значений, возвращаемых функцией MsgBox() в зависимости от нажатой в диалоге кнопки.

Значение Константа Word Надпись на кнопке
1 vbOK OK
2 vbCancel Cancel
3 vbAbort Abort
4 vbRetry Retry
5 vbIgnore Ignore
6 vbYes Yes
7 vbNo No

Пример:

Dim RunMacro As Byte 'Задать целочисленную переменную минимального размера
RunMacro = MsgBox("Заменить дефисы в документе?", 4 + 48, "Замена дефисов")
	'Запустить диалог с кнопками Yes+No и картинкой "Внимание!"
	'Целое число, соответствующее нажатой кнопке, запомнить в RunMacro
If RunMacro = 6 Then 'Нажато Yes (вместо 6 можно записать vbYes)
	Selection.HomeKey Unit:=wdStory
	'Перейти на начало документа и продолжить программу после End If
Else 'Нажато не Yes (No для нашего примера)
	Exit Sub 'Выйти из программы, не делая ничего
End If
... Основная программа

Диалог будет выглядеть так:

Можно сказать, что в нем допущена интерфейсная ошибка, так как нажатие клавиши Esc не позволит закрыть диалог.
Для комфортности лучше использовать одновременно кнопки Yes, No и Cancel.
Для доработки понадобится только заменить в тексте программы 4 на 3: ведь нажатие на Cancel обработается также, как и No (выход из программы).

Обратите внимание! Вместо 4+48, можно было бы записать сразу результат сложения (52).
Программа выполнилась бы чуточку быстрее, но редактирование человеком стало бы сложнее.
Также можно заменить эту форму сложением программных констант: vbYesNo+vbExclamation, что легче понять при чтении.

Идеальным(?) решением было бы добавление кнопки Cancel, как показано ниже.

   RunMacro = MsgBox("Заменить дефисы в документе?", 3 + 48, "Замена дефисов")

См. также Экранные формы (Forms).

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