Excel vba всплывающее окно

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

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

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

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

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

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

Функция InputBox в VBA

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

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

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

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

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

Sub GetName()

    Dim UserName As String

    Dim FirstSpace As Integer

    Do Until UserName <> «»

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

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

    Loop

    FirstSpace = InStr(UserName, » «)

    If FirstSpace <> 0 Then

        UserName = Left(UserName, FirstSpace 1)

    End If

    MsgBox «Привет « & UserName

End Sub

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

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

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

Sub GetWord()

    Dim TheWord As String

    Dim p As String

    Dim t As String

    p = Range(«A1»)

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

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

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

        MsgBox «Верно.»

    Else

        MsgBox «Не верно.»

    End If

End Sub

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

Метод Excel InputBox

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

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

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

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

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

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

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

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

Sub EraseRange()

    Dim UserRange As Range

    On Error GoTo Canceled

    Set UserRange = Application.InputBox _

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

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

        Default:=Selection.Address, _

        Type:=8)

    UserRange.Clear

    UserRange.Select

Canceled:

End Sub

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

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

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

Функция VBA MsgBox

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

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

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

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

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

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

Sub MsgBoxDemo()

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

End Sub

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

Sub GetAnswer()

    Dim Ans As Integer

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

    Select Case Ans

        Case vbYes

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

        Case vbNo

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

    End Select

End Sub

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

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

Sub GetAnswer2()

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

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

    Else

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

    End If

End Sub

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

Private Function ContinueProcedure() As Boolean

   Dim Config As Integer

   Dim Ans As Integer

   Config = vbYesNo + vbQuestion + vbDefaultButton2

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

   If Ans = vbYes Then ContinueProcedure = True _

      Else ContinueProcedure = False

End Function

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

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

If Not ContinueProcedure() Then Exit Sub

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

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

Sub MultiLine()

    Dim Msg As String

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

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

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

    MsgBox Msg

End Sub

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

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

Sub ShowRange()

    Dim Msg As String

    Dim r As Integer, c As Integer

    Msg = «»

    For r = 1 To 10

        For c = 1 To 3

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

            If c <> 3 Then Msg = Msg & vbTab

            Next c

            Msg = Msg & vbCrLf

        Next r

    MsgBox Msg

End Sub

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

Метод Excel GetOpenFilename

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

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

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

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

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

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

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

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

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

Sub GetImportFileName()

    Dim Filt As String

    Dim FilterIndex As Integer

    Dim FileName As Variant

    Dim Title As String

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

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

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

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

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

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

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

    FilterIndex = 3

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

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

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

    FileName = Application.GetOpenFilename _

        (FileFilter:=Filt, _

         FilterIndex:=FilterIndex, _

         Title:=Title)

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

    If FileName = False Then

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

        Exit Sub

    End If

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

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

End Sub

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

Sub GetImportFileName2()

    Dim Filt As String

    Dim FilterIndex As Integer

    Dim FileName As Variant

    Dim Title As String

    Dim i As Integer

    Dim Msg As String

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

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

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

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

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

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

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

    FilterIndex = 5

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

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

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

    FileName = Application.GetOpenFilename _

        (FileFilter:=Filt, _

         FilterIndex:=FilterIndex, _

         Title:=Title, _

         MultiSelect:=True)

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

    If Not IsArray(FileName) Then

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

        Exit Sub

    End If

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

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

        Msg = Msg & FileName(i) & vbCrLf

    Next i

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

End Sub

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

Метод Excel GetSaveAsFilename

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

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

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

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

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

Sub GetAFolder()

    With Application.FileDialog(msoFileDialogFolderPicker)

        .InitialFileName = Application.DefaultFilePath & «»

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

        .Show

        If .SelectedItems.Count = 0 Then

            MsgBox «Отменено»

        Else

            MsgBox .SelectedItems(1)

        End If

    End With

End Sub

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

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

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

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

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

Application.CommandBars.ExecuteMso("SheetUnhide")

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

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

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

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

Application.CommandBars.ExecuteMso("FormatCellsFontDialog")

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

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

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

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

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

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

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

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

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

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

Sub DisplayDataForm()

    Range(«A1»).Select

    ActiveSheet.ShowDataForm

End Sub

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

Create a pop-up message box in Excel using VBA Macros. This allows you to show a message to the user and to get input back, depending on which buttons were clicked in the pop-up message.

To output a message in Excel, we use the MsgBox function. Below, you will find many examples that should suit your needs.

Sections:

Syntax

Example 1 — Output Basic Text

Example 2 — Add Buttons to the Message Box

Example 3 — Figure Out Which Button Was Clicked

Example 4 — Do Something After the User Clicks a Button

Example 5 — Change MsgBox Appearance

Notes

Syntax

MsgBox(prompt, [buttons], [title], [helpfile], [context])
Argument Description
Prompt

The text that will be in the message box. This is the only required argument for the MsgBox function.

[Buttons]

Allows you to display different buttons and icons in the message box.

[Title]

Text that appears in the title bar of the message box.

[Helpfile]

Not needed. Allows for a specific help file to be used.

[Context]

Not needed. Required if the helpfile argument is used.

[] means it is an optional argument.

Button Arguments

These are the values that can be entered for the buttons argument. You will use the VB Codes to add them to the message box. Examples below will include some of these options so you can better understand them.

VB Code Description Value

vbOKOnly

OK Button. Default.

0

vbOKCancel

OK and Cancel buttons.

1

vbAbortRetryIgnore

Abort, Retry, and Ignore buttons.

2

vbYesNoCancel

Yes, No, and Cancel buttons.

3

vbYesNo

Yes and No buttons.

4

vbRetryCancel

Retry and Cancel buttons.

5

vbCritical

Displays the Critical Message icon in the message box window.

16

vbQuestion

Displays the Warning Query icon in the message box window.

32

vbExclamation

Displays the Warning Message icon in the message box window.

48

vbInformation

Displays the Information Message icon in the message box window.

64

vbDefaultButton1

Selects the first button in the message box by default.

0

vbDefaultButton2

Selects the second button in the message box by default.

256

vbDefaultButton3

Selects the third button in the message box by default.

512

vbDefaultButton4

Selects the fourth button in the message box by default.

768

vbApplicationModal

Application modal; the user must respond to the message box before continuing work in Excel.

0

vbSystemModal

System modal; all applications are suspended until the user responds to the message box.

4096

VbMsgBoxSetForeground

Specifies the message box window as the foreground window

65536

vbMsgBoxRight

Text is right aligned

524288

Values Returned from Button Clicks in the Message Box

When a user clicks one of the buttons that are in the message box, a value will be returned to VBA; that value corresponds to the button that was clicked and is listed below.

Button Clicked Returned Constant Returned # Value

OK

vbOK

1

Cancel

vbCancel

2

Abort

vbAbort

3

Retry

vbRetry

4

Ignore

vbIgnore

5

Yes

vbYes

6

No

vbNo

7

Example 1 — Output Basic Text

Basic message box with text.

This is the simplest form of outputting a message.

MsgBox "Hi, this is my message."

a63ffa7cd8882f6ceadecdb8df1f21ba.jpg

Running the macro we get this:

c46b3081178c9e6626f8785ee388b478.jpg

Remember, the OK button is there by default and clicking that simply closes the pop-up message box window.

Example 2 — Add Buttons to the Message Box

Message box with multiple buttons.

MsgBox "Hi, this is my message.", vbYesNoCancel

db0f8fdeac20a772711bf8eafc93ce33.jpg

I added a comma after the display text and then input one of the VB codes from the Button Arguments list above.

2dea7d7b5e6391765e3a6b6661789ebd.jpg

Run the macro and we get this in Excel:

f8ac44abed8da3166c9ce60897767240.jpg

Example 3 — Figure Out Which Button Was Clicked

When a button is clicked, it sends a value back to Excel. Now, we need to capture that value so we can do something with it.

response = MsgBox("Hi, this is my message.", vbYesNoCancel)

4201571bd7a681c0b0102d55a8ff2ec2.jpg

All we have to do is to set a variable equal to the output of the MsgBox function. Here, the variable response is equal to the output of the function, which means that we type response =  and then the msgbox function.

Note also that there are now parentheses surrounding the arguments for the MsgBox function; these weren’t included before because they weren’t needed. Often, they aren’t used when creating simple pop-up windows.

I will now output the variable response into a Msgbox of its own so you can see the value it returns after a button was clicked.

Here is the final code for this example:

b6056271ee5283726f0493532c267437.jpg

Run it and you get this:

7ee7a2cc2dd7f2214b8abc8f2e9773a9.jpg

Click one of the buttons and the next message box will open with the value that was returned as a result of the button click in the first window.

ad4d29f171f3b99745743da22c860edb.jpg

A 6 is returned, which means the button Yes was clicked. We know this from the table above «Values Returned from Button Clicks in the Message Box», which lists the values that each button click will return.

Example 4 — Do Something After the User Clicks a Button

Now that you know how to determine which button was clicked, let’s do something useful with it.

I will make a simple IF statement that checks which button was clicked and outputs a message based on that.

Sub button_action_msgbox()

response = MsgBox("Hi, this is my message.", vbYesNo)

If response = 6 Then
    MsgBox "You clicked Yes"
ElseIf response = 7 Then
    MsgBox "You clicked No"
End If

End Sub

74e8e0e525ee2b884813984e0bb0585f.jpg

Run the macro:

5a3ec2e9d11e8f438483a7b79788801a.jpg

Hit one of the buttons and the next part of the macro will run and the corresponding msgbox will appear:

1a40178ea6aa380be3256decf2a543f8.jpg

At this point, we have created a useful pop-up message box that solicits feedback and does something with that feedback.

Example 5 — Change MsgBox Appearance

You can add some additional things to the pop-up window to change its look and feel and here I will include some of those options, including a custom title for the window.

Sub button_style_msgbox()

MsgBox _
    "Hi, this is my message.", _
    vbOKOnly + vbInformation, _
    "Custom Title"

End Sub

8d756ee11ae6c7f7f5dbd0ba45030a52.jpg

First, notice that I used «_» at the end of each line so that I could place this piece of code on multiple lines.

Second, notice that there is now a custom title called Custom Title that will appear for the msgbox.

Third, notice that there is more than one option for the buttons argument and that each argument is separated with a plus sign (+) like this: vbOKOnly + vbInformation.

Run the macro and we get this:

12471f5ba0f2c25a758a04457f3b1079.jpg

The option vbOKOnly meant there would be only an OK button. The option vbInformation put that image with the i inside the blue circle in there. The custom title appears in the upper-left corner of the pop-up message box window.

Notes

These are a few examples that should get you comfortable using the Message Box pop-up window feature in macros in Excel.

This is a great way to give some information to your user that they must process or at least must reply to in some way before continuing.

Make sure to download the sample file attached to this tutorial to get all of the sample VBA Macro codes.

Хитрости »

19 Октябрь 2014              101406 просмотров


Работа с диалогами

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

  • сообщить пользователю о выполнении кода;
  • получить от пользователя подтверждение на выполнение того или иного действия;
  • запросить какие-то данные(число, текст для поиска, диапазон поиска и т.п.).

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

Из основных можно выделить три типа:
MsgBox — окно информирования пользователя с возможностью запроса действия (Да, Нет, Отмена и т.п.);
InputBox — окно запроса текстовой информации от пользователя (текст для поиска, дата, число и т.п.);
Application.InputBox — чуть более расширенная версия InputBox с возможностью указания не только текста и чисел, но и выделения диапазона ячеек (например для указания ячеек, в которых осуществлять поиск значения или которые необходимо закрасить).

  • Информационный диалог MsgBox
  • MsgBox, автоматически закрываемый по истечении указанного времени
  • Диалог ввода информации пользователем InputBox
  • Диалог выбора диапазона Application.InputBox

ИНФОРМАЦИОННЫЙ ДИАЛОГ MSGBOX

MsgBox
Самый простой тип. Используется для информирования пользователя. Как правило применяется по окончании выполнения кода:

MsgBox Promt, [Buttons], [Title], [HelpFile], [Context]

Обязательным к указанию является только первый параметр —

Promt

, в котором указывается непосредственно сообщение для вывода:

MsgBox "Обработка завершена"

Все остальные параметры указывать не обязательно, но их использование несколько расширяет возможности данного диалогового окна.
Buttons — указывается тип выводимых кнопок и стиль окна. По умолчанию применяется vbOKOnly — одна только кнопка Ок:

'показываем окно с кнопкой по умолчанию и типом важного сообщения
MsgBox "Обработка завершена", vbCritical

Доступны значения:

Значение Числовая константа Описание
vbOKOnly 0 Отображает только кнопку OK
vbOKCancel 1 Отображает кнопки ОК и Отмена
vbAbortRetryIgnore 2 Отображает кнопки Прервать, Повтор и Пропустить
vbYesNoCancel 3 Отображает кнопки Да, Нет и Отмена
vbYesNo 4 Отображает кнопки Да и Нет
vbRetryCancel 5 Отображает кнопки Повтор и Отмена
vbCritical 16 Отображает значок важного сообщения
vbQuestion 32 Отображает значок важного запроса
vbExclamation 48 Отображает значок предупреждающего сообщения
vbInformation 64 Отображает значок информационного сообщения
vbDefaultButton1 0 По умолчанию выделена первая кнопка
vbDefaultButton2 256 По умолчанию выделена вторая кнопка
vbDefaultButton3 512 По умолчанию выделена третья кнопка
vbDefaultButton4 768 По умолчанию выделена четвертая кнопка
vbApplicationModal 4098 Все приложения приостанавливают свою работу до момента, пока пользователь ответит на запрос в окне сообщения (работает не во всех случаях)
vbMsgBoxHelpButton 16384 Показываются кнопки Ок и Help

Константы Buttons могут быть объединены между собой. Ниже приведен код, который показывает диалоговое окно с возможностью выбора одного из трех вариантов — Прервать, Повтор, Пропустить:

'---------------------------------------------------------------------------------------
' Procedure : test
' DateTime  : 19.10.2014 19:24
' Author    : The_Prist(Щербаков Дмитрий)
'             WebMoney - R298726502453; Яндекс.Деньги - 41001332272872
'             http://www.excel-vba.ru
' Purpose   : Процедура показывает диалоговое окно с возможностью выбора одного из трех вариантов:
'             Прервать, Повтор, Пропустить
'             По умолчанию выделена кнопка Прервать, т.к. иное не указано
'---------------------------------------------------------------------------------------
Sub test()
    Dim lRetVal As Long 'для получения выбранного значения
Retry_:
    lRetVal = MsgBox("Обработка завершена", vbAbortRetryIgnore + vbQuestion)
    Select Case lRetVal
    Case vbAbort    '3/Прервать/Abort
        Exit Sub    'выходим из процедуры
    Case vbRetry    '4/Повтор/Retry
        GoTo Retry_ 'переход на метку Retry_
    Case vbIgnore   '5/Пропустить/Ignore
    End Select
End Sub

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

'---------------------------------------------------------------------------------------
' Procedure : test
' DateTime  : 19.10.2014 19:24
' Author    : The_Prist(Щербаков Дмитрий)
'             WebMoney - R298726502453; Яндекс.Деньги - 41001332272872
'             http://www.excel-vba.ru
' Purpose   : Процедура показывает диалоговое окно с возможностью выбора одного из трех вариантов:
'             Прервать, Повтор, Пропустить
'             По умолчанию выделена кнопка Пропустить(3-я по счету - значит vbDefaultButton3)
'---------------------------------------------------------------------------------------
Sub test()
    Dim lRetVal As Long 'для получения выбранного значения
Retry_:
    lRetVal = MsgBox("Обработка завершена", vbAbortRetryIgnore + vbQuestion + vbDefaultButton3)
    Select Case lRetVal
    Case vbAbort    '3/Прервать/Abort
        Exit Sub    'выходим из процедуры
    Case vbRetry    '4/Повтор/Retry
        GoTo Retry_ 'переход на метку Retry_
    Case vbIgnore   '5/Пропустить/Ignore
    End Select
End Sub

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

Sub test()
    Dim lRetVal As Long 'для получения выбранного значения
Retry_:
    lRetVal = MsgBox("Обработка завершена", 2 + 32 + 512)
    Select Case lRetVal
    Case 3    'vbAbort
        Exit Sub    'выходим из процедуры
    Case 4    'vbRetry
        GoTo Retry_ 'переход на метку Retry_
    Case 5   'vbIgnore
    End Select
End Sub

Нетрудно после этого предположить, что можно указать просто сумму данных чисел:

MsgBox "Обработка завершена", 546

Доступные константы значений возврата:

Константа Значение Нажатая кнопка
vboK 1 ОК
vbCancel 2 Отмена
vbAbort 3 Прервать
vbRetry 4 Повтор
vblgnore 5 Пропустить
vbYes 6 Да
vbNo 7 Нет

Title — указывается текст заголовка окна. Например, можно указать либо что это ошибка, либо имя своего приложения:

MsgBox "Обработка завершена", vbOKOnly, "Мое приложение"

HelpFile — указывается имя файла-справки в формате HLP. Применяется, если параметр Buttons указан как vbMsgBoxHelpButton. Файл справки должен существовать.
Context — целое число. Указывается индекс страницы файла-справки, которую необходимо открыть. Указывается только если указан параметр HelpFile.

Небольшой практический пример применения простого диалогового окна MsgBox.
Цель процедуры(макроса): очистить все ячейки листа.
Согласитесь, что неплохо бы перед этим запросить у пользователя решение — он согласен с этим и это является обдуманным решением или случайностью?

'---------------------------------------------------------------------------------------
' Procedure : ClearRange
' DateTime  : 19.10.2014 20:06
' Author    : The_Prist(Щербаков Дмитрий)
'             WebMoney - R298726502453; Яндекс.Деньги - 41001332272872
'             http://www.excel-vba.ru
' Purpose   :
'---------------------------------------------------------------------------------------
Sub ClearRange()
    Dim lRetVal As Long 'для получения выбранного значения
    lRetVal = MsgBox("Все данные выделенных ячеек будут удалены." & _
        Chr(10) & "Действительно хотите продолжить?", _
        vbYesNo + vbQuestion, "Запрос на выполнение")
    If lRetVal = vbNo Then
        Exit Sub 'выходим из процедуры без выполнения
    End If
    Selection.Clear
End Sub

Так же на странице Полезные программы для Excel и VBA можно найти программу MsgBox Generator, которая просто и наглядно формирует коды показа MsgBox.


MsgBox, автоматически закрываемый по истечении указанного времени

Диалог MsgBox удобен, если надо проинформировать пользователя о каких-то событиях или предоставить ему выбор Да или Нет. Но в тоже время есть один недостаток: этот диалог не закроется, пока пользователь не нажмет хоть какую-то кнопку. Но бывает необходимо просто проинформировать и закрыть окно независимо от реакции пользователя. Показали окно, подождали секунд 5-7 и даже если пользователь ничего не нажал — закрыли окно и продолжили выполнение кода. Стандартно такой опции в MsgBox нет. Однако можно использовать функции API(это встроенные в ОС Windows функции, которые можно вызывать из любого языка программирования).
Код такого диалога:

Declare Function MessageBoxTimeOut Lib "User32" Alias "MessageBoxTimeoutA" _
                        (ByVal hwnd As Long, ByVal lpText As String, _
                         ByVal lpCaption As String, ByVal uType As VbMsgBoxStyle, _
                         ByVal wLanguageId As Long, ByVal dwMilliseconds As Long) As Long
Sub AutoCloseMsgBox()
    Const lSeconds As Long = 5
    MessageBoxTimeOut 0, "Отчет сформирован. Это окно закроется автоматически через 5 секунд", "www.excel-vba.ru", _
                         vbInformation + vbOKOnly, 0&, lSeconds * 1000
End Sub

Основную роль здесь играет строка:

Declare Function MessageBoxTimeOut Lib "User32" Alias "MessageBoxTimeoutA" _
                        (ByVal hwnd As Long, ByVal lpText As String, _
                         ByVal lpCaption As String, ByVal uType As VbMsgBoxStyle, _
                         ByVal wLanguageId As Long, ByVal dwMilliseconds As Long) As Long

это и есть сама функция, создающая MsgBox.
Главное: эта строка должна располагаться в самом верху стандартного модуля(в области объявлений, перед всеми процедурами и функциями).

Так же следует помнить, что это функция API и в некоторых версиях Excel именно в таком виде может не работать — вся строка будет подсвечена красным. Если проявился такой эффект, то можно просто добавить ключевое слово PtrSafe, отвечающее за совместимость функции с 64-битными ОС:

Declare PtrSafe Function MessageBoxTimeOut Lib "User32" Alias "MessageBoxTimeoutA" _
                        (ByVal hwnd As Long, ByVal lpText As String, _
                         ByVal lpCaption As String, ByVal uType As VbMsgBoxStyle, _
                         ByVal wLanguageId As Long, ByVal dwMilliseconds As Long) As Long

Помимо очевидного текста сообщения и заголовка, который можно заменить на свой, главное внимание уделим константе lSeconds. Она отвечает за количество секунд показа сообщения. В примере выше сообщение будет показано на 5 секунд, после чего закроется само собой, если ранее не была нажата кнопка Ок.
Если необходимо показать сообщение на 10 секунд, то надо лишь заменить 5 на 10:
Const lSeconds As Long = 10
Параметр uType работает точно так же, как параметр Buttons у стандартного MsgBox. Т.е. можно комбинировать различные виды кнопок и использовать этот MsgBox как стандартный, но при этом закрыть его автоматически, если пользователь случайно «уснул» или ему лень/некогда что-то нажимать:

Sub AutoCloseMsgBox()
    Const lSeconds As Long = 10
    Dim retval
    retval = MessageBoxTimeOut(0, "Файлы обработаны. Вывести список?" & vbNewLine & _
                                  "Если действие не будет выбрано окно закроется через 10 секунд", "www.excel-vba.ru", _
                                  vbInformation + vbYesNo, 0&, lSeconds * 1000)
    If retval = 6 Then 'была нажата кнопка Да(Yes)
        'выводим отчет
    Else 'была нажата кнопка Нет(No) или окно закрылось само
        'другое действие
    End If
End Sub

ДИАЛОГ ВВОДА ИНФОРМАЦИИ ПОЛЬЗОВАТЕЛЕМ — INPUTBOX
InputBox

позволяет запросить от пользователя любую текстовую информацию.
InputBox

InputBox Promt, [Title], [DefaultValue], [XPos], [YPos], [HelpFile], [Context]

Так же как и с MsgBox обязательным аргументом для указания является только

Promt

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

Dim vRetVal 'для получения выбранного значения
vRetVal = InputBox("Укажите значение для поиска:", "Запрос данных", "")
If vRetVal = "" Then Exit Sub 'завершаем процедуру, если строка пуста

Title — текст, отображаемый в заголовке окна. В приведенном выше примере это «Запрос данных».
DefaultValue — значение, которое будет показано в поле ввода до указания значения пользователем. Как правило оно указывается в случаях, когда требуемое значение изменяется редко по запросу пользователя, но возможность такую оставить все же требуется.
Пример: необходимо по нажатию кнопки удалять всегда столбец 5. Но иногда столбец в отчете смещается и требуется запрашивать у пользователя реальный номер столбца:

Sub DelCols()
    Dim vRetVal 'для получения выбранного значения
    vRetVal = InputBox("Укажите номер столбца для удаления(целое число):", "Запрос данных", 5)
    'используем Val для преобразования текста vRetVal в число
    'Val() преобразует число как текст в число.
    'Если указан текст(например "третий") - он будет преобразован в 0
    vRetVal = Val(vRetVal)
    If Val(vRetVal) = 0 Then
        MsgBox "Номер столбца должен быть целым числом больше нуля!", vbCritical, "DelCols"
        Exit Sub
    End If
    Columns(vRetVal).Delete
End Sub

Важно знать: InputBox всегда возвращает только текст. Даже если указать — 5 — он вернет «5». В некоторых случаях это может привести к ошибке типов данных, поэтому я привел выше один из примеров преобразования типов данных к нужному.
Так же по прошествии какого-то времени появится вопрос, как отследить нажатие кнопки Отмена. Ведь ориентир на vRetVal = «» не всегда верен, иногда надо принять пустое значение(в случаях, скажем, замены значений) и отследить именно нажатие Отмена. Сделать это можно так:

vRetVal = InputBox("Укажите номер столбца для удаления(целое число):", "Запрос данных", "")
 
If StrPtr(vRetVal) = 0 Then
    MsgBox "Нажата кнопка Отмена. Процедура прервана", vbCritical, "DelCols"
    Exit Sub
End If

Больше всего вопросов здесь явно вызовет StrPtr. Эта специальная функция VBA, которая указывает, что переданы некие строковые данные. Если никаких данных не передавалось(а в случае с нажатием кнопки Отмена так и есть) указатель вернет 0. Если какие-то данные были переданы или нажата кнопка Ок(автоматом будет передана строка нулевой длины) — указатель StrPtr вернет значение отличное от нуля.

XPos — положение окна InputBox в твипах по горизонтали относительно левого края экрана. Следует учитывать, что именно относительно экрана, а не окна Excel.
YPos — положение окна InputBox в твипах по вертикали относительно верхнего края экрана.
HelpFile — указывается имя файла-справки в формате HLP. В отличие от MsgBox указание файла допускается при любых значениях. При этом к уже имеющимся в InputBox кнопкам добавляется еще одна — Help, которая и отвечает за вызов справки.
Context — целое число. Указывается индекс страницы файла-справки, которую необходимо открыть при нажатии кнопки Help. Указывается только если указан параметр HelpFile.

В дополнение приведу классический пример применения InputBox — выполнение процедуры только после введения пароля:

Sub ClearAllCells()
Dim vRetVal
vRetVal = InputBox("Введите пароль:", "Авторизация", "")
 
If StrPtr(vRetVal) = 0 Then 'Нажата кнопка Отмена
    Exit Sub
End If
 
'если пароль неверный - завершаем процедуру без выполнения действий
If vRetVal <> "1234" Then
    MsgBox "Введенный пароль неверный", vbCritical, "ClearAllCells"
    Exit Sub
End If
'будет выполнено только если введен правильный пароль - 1234
'полная очистка всех ячеек активного листа
ActiveSheet.Cells.Clear
End Sub

А вот еще один пример применения — запрос имени пользователя и запись его в лист LOG, чтобы можно было отследить кто и когда открывал файл. При этом если пользователь нажал Отмена, то книга закроется, а если не укажет имя пользователя — появится сообщение и заново запрос. И так до тех пор, пока имя пользователя не будет введено или не будет нажата кнопка Отмена:

Private Sub Workbook_Open()
    'ThisWorkbook - Обращение к книге с кодом
    'Но из модуля самой книги можно обращаться и проще - Me
    ThisWorkbook.Visible = False
    Dim user As String, lastrow As Long
    'цикл, пока не будут указаны данные пользователя
    Do While user = ""
        user = InputBox("Введите имя пользователя:", "Авторизация", "")
        If StrPtr(user) = 0 Then
            MsgBox "Приложение будет закрыто", vbCritical, "Авторизация"
            ThisWorkbook.Close
            Exit Sub
        End If
        If user = "" Then
            MsgBox "Не указано имя пользователя!", vbCritical, "Авторизация"
        End If
    Loop
    With ThisWorkbook.Worksheets("LOG")
        'получаем последнюю заполненную ячейку на листе "LOG"
        lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        'записываем имя пользователя
        .Cells(lastrow + 1, 1) = user
        'записываем время входа
        .Cells(lastrow + 1, 2) = Now
    End With
End Sub

Что важно: этот код записывается в модуль ЭтаКнига(ThisWorkbook) и тогда при любом открытии книги будет появляться запрос на имя пользователя.

Так же некоторые примеры применения InputBox можно найти в статьях на сайте. Например:
Как удалить строки по условию?
Как массово изменить гиперссылки?


ДИАЛОГ ВВОДА ИНФОРМАЦИИ ПОЛЬЗОВАТЕЛЕМ — APPLICATION.INPUTBOX

 Applicatoin.InputBox
В общем-то данный диалог мало отличается от обычного InputBox, за исключением типов возвращаемых данных. У данного диалога намного богаче функционал определения типов данных.

InputBox Promt, [Title], [DefaultValue], [Left], [Top], [HelpFile], [HelpContextID], [Type]
почти все параметры аналогичны таким же параметрам в InputBox.
Promt — текст, отображаемый на самой форме. Иначе говоря — сама суть показа диалога.
Title — текст, отображаемый в заголовке окна. В приведенном выше примере это «Запрос данных».
DefaultValue — значение, которое будет показано в поле ввода до указания значения пользователем.
Left — положение окна InputBox в поинтах по горизонтали относительно левого края экрана. В отличие от простого InputBox положение определяется на основании расположения самого окна Excel, а не экрана.
Top — положение окна InputBox в твипах по вертикали относительно верхнего края экрана.
HelpFile — указывается имя файла-справки в формате HLP. В отличие от MsgBox указание файла допускается при любых значениях. При этом к уже имеющимся в InputBox кнопкам добавляется еще одна — Help, которая и отвечает за вызов справки. Сам вызов справки осуществляется путем нажатия на иконку со знаком вопроса в заголовке диалога.
HelpContextID — целое число. Указывается индекс страницы файла-справки, которую необходимо открыть при нажатии кнопки Help. Указывается только если указан параметр HelpFile.
Type — целое число. Указывается одно из предустановленных значений, указывающих диалогу Application.InputBox тип данных, которые предполагается получить от пользователя. Ниже приведен листинг кода, демонстрирующий запрос данных всех типов с описанием ограничений и нюансов.

    Dim vRetVal 'для получения выбранного значения
    'запрос формулы - Type:=0
    'возвращает либо произвольный текст, указанный в поле или ссылку на указанную ячейку в стиле R1C1
    vRetVal = Application.InputBox("Укажите формулу:", "Запрос данных", "", Type:=0)
    'запрос числа - Type:=1
    'возвращает число. Не даст ввести текст, выдав сообщение об ошибке
    vRetVal = Application.InputBox("Укажите любое число:", "Запрос данных", "", Type:=1)
    'запрос текст - Type:=2
    'возвращает указанный текст. При указании числа оно будет в виде текста: 1="1"
    vRetVal = Application.InputBox("Укажите любой текст:", "Запрос данных", "", Type:=2)
    'запрос логического значения True или False - Type:=4
    'значение указывает в текущей локализации офиса
    'для русской это ИСТИНА или ЛОЖЬ
    'так же можно указать универсальные числовые константы - 1 или 0. 1 - ИСТИНА; 0 - ЛОЖЬ
    'Не даст ввести иные значения, выдав сообщение об ошибке
    'возвращает указанное логическое значение в английской локализации
    vRetVal = Application.InputBox("Укажите ИСТИНА или ЛОЖЬ:", "Запрос данных", "", Type:=4)
    'запрос диапазона - Type:=8
    'возвращает ссылку на диапазон
    'При получении такого значения обязательно следует использовать оператор Set
    'В противном случае вернет значение массива(Array), содержащего значения указанных ячеек
    'при указании через Set и нажатии Отмена будет ошибка VBA
    Set vRetVal = Application.InputBox("Укажите диапазон для очистки ячеек:", "Запрос данных", "", Type:=8)
    'запрос значения ошибки #Н/Д - Type:=16
    'всегда возвращает значение ошибки #Н/Д независимо от введенного значения
    vRetVal = Application.InputBox("Укажите диапазон для очистки ячеек:", "Запрос данных", "", Type:=16)
    'запрос диапазона ячеек для создания массива - Type:=64
    'возвращает массив ячеек с границами начала от 1(Option Base 1)
    'если указать всего одну ячейку vRetVal будет содержать значение этой ячейки, а не массив
    vRetVal = Application.InputBox("Укажите диапазон для создания массива:", "Запрос данных", "", Type:=64)

Конечно, чаще всего используют Type:=8, т.к. это избавляет от необходимости рисования своих форм и прочих заморочек для запроса указания диапазона от пользователя. Еще раз обращаю внимание, что для Type:=8 необходим ключевой оператор присвоения Set, т.к. в результате необходимо получить именно диапазон(т.е. объект). Ниже приведена процедура, которая запрашивает диапазон для очистки и корректно обрабатывает ситуацию при нажатии кнопки Отмена(т.е. не показывает никаких ошибок пользователю, а просто не выполняется). Стандартно при нажатии Отмена процедура завершается с ошибкой VBA вида Type Mismatch, что не очень грамотно с точки зрения взаимодействия с пользователем — он не должен видеть внутренние ошибки:

'---------------------------------------------------------------------------------------
' Procedure : ClearCells
' DateTime  : 19.10.2014 22:53
' Author    : The_Prist(Щербаков Дмитрий)
'             WebMoney - R298726502453; Яндекс.Деньги - 41001332272872
'             http://www.excel-vba.ru
' Purpose   :
'             Запрашиваем диапазон ячеек для очистки.
'             По умолчанию заносится диапазон выделенных на момент запуска ячеек
'---------------------------------------------------------------------------------------
Sub ClearCells()
    Dim vRetVal 'для получения выбранного значения
 
    On Error Resume Next
    Set vRetVal = Application.InputBox("Укажите диапазон для очистки ячеек:", "Запрос данных", Selection.Address, Type:=8)
    If vRetVal Is Nothing Then 'нажата кнопка Отмена - диапазон не выбран
        MsgBox "Отмена выполнения", vbCritical, "Нет данных"
        Exit Sub 'завершаем процедуру, т.к. ячейки не выбраны
    End If
    'диапазон выбран - очищаем ячейки
    vRetVal.Clear
End Sub

Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

The VBA MsgBox function is used to display messages to the user in the form of a message box.

We can configure the message box to provide the user with a number of different buttons such as Yes, No, Ok, Retry, Abort, Ignore and Cancel. The MsgBox function will then return the button that was clicked.

Related Links

VBA Userforms

Basic VBA MsgBox Examples

In most cases, you will use MsgBox to simply display a message or to ask the user to click Yes/No or Ok/Cancel. The following code shows how to display a simple message box:

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

    ' Basic message
    MsgBox "There is no data on this worksheet "

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

End Sub

MsgBox Example

VBA MsgBox Parameters

The parameters of the message box are as follows:

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

prompt – This is the message text that will be displayed.

buttons[optional] – This parameter does many things including setting the buttons, icons, select button, modal type etc. If this parameter is not used a message box with the Ok button and no icon is displayed. See the next section for more about this parameter.

title[optional] – this is the title that will appear at the top of the message box. The default is “Microsoft Excel”.

helpfile, context[optional] – These parameters are used to reference a help file and location of specific help text. It is very unlikely you use this unless you are creating an application for a third party and help files are a requirement.

VBA MsgBox Return Values

The following are all the return values for the MsgBox function:

vbOk
vbCancel
vbAbort
vbRetry
vbIgnore
vbYes
vbNo

Each of these values represents a button that was clicked.

VBA MsgBox Yes No

We can use the message box to get a simple response from the user. For example, we can ask the user a question and they can respond by clicking on the Yes or No button. The return value from the MsgBox function tells us which button was clicked.

VBA MsgBox

If we want to get a Yes/No response from the user we can do it with the following code:

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

    ' Display a messagebox based on the response
    If MsgBox("Do you wish to continue? ", vbYesNo) = vbYes Then
        MsgBox "The user clicked Yes"
    Else
        MsgBox "The user clicked No"
    End If

End Sub

Note: When we return a value from the message box we must use parenthesis around the parameters or we will get the “Expected end of statement” error.

We can also use a variable to store the response from the MsgBox. We would normally do this if we want to use the response more than once. For example, if there were three buttons:

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

    Dim resp As VbMsgBoxResult
    ' Store MsgBox response in a variable
    resp = MsgBox("Do you wish to continue? ", vbAbortRetryIgnore)
    
    ' Display Ok/Cancel buttons and get response
    If resp = vbAbort Then
        MsgBox "The user clicked Abort"
    ElseIf resp = vbRetry Then
        MsgBox "The user clicked Retry"
    ElseIf resp = vbIgnore Then
        MsgBox "The user clicked Ignore"
    End If

End Sub

VBA MsgBox Button Constants

The button parameter of MsgBox allows us to configure the message box in many ways. The table below shows the different options:

Constant Group Type Description
vbOKOnly 1 Buttons Ok button.
vbOKCancel 1 Buttons Ok and cancel buttons.
vbAbortRetryIgnore 1 Buttons Abort, Retry and Ignore buttons.
vbYesNoCancel 1 Buttons Yes, No and Cancel buttons.
vbYesNo 1 Buttons Yes and No buttons.
vbRetryCancel 1 Buttons Retry and Cancel buttons.
vbCritical 2 Icon Critical Message icon.
vbQuestion 2 Icon Question mark icon.
vbExclamation 2 Icon Warning Message icon.
vbInformation 2 Icon Information Message icon.
vbDefaultButton1 3 Default button Set button 1 to be selected.
vbDefaultButton2 3 Default button Set button 2 to be selected.
vbDefaultButton3 3 Default button Set button 3 to be selected.
vbDefaultButton4 3 Default button Set button 4 to be selected. Note that there will only be four buttons if the help button is included with vbAbortRetryIgnore or vbYesNoCancel.
vbApplicationModal 4 Modal Cannot access Excel while the button is displayed. Msgbox is only displayed when Excel is the active application.
vbSystemModal 4 Modal Same as vbApplicationModal but the message box is displayed in front of all applications.
vbMsgBoxHelpButton 5 Other Adds a help button
vbMsgBoxSetForeground 5 Other Sets the message box windows to be the foreground window
vbMsgBoxRight 5 Other Right aligns the text.
vbMsgBoxRtlReading 5 Other Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

These constants work as follows:

  1. The constants in group 1 are used to select the buttons.
  2. The constants in group 2 are used to select icons.
  3. The constants in group 3 are used to select which button is highlighted when the message box appears.
  4. The constants in group 4 are used to set the modal type of the message box.
  5. The constants in group 5 are used for various settings.

When we use MsgBox, we can combine items from each group by using the plus sign. For example:

MsgBox "Example 1" ,vbOkCancel + vbCritical + vbDefaultButton1 + vbApplicationModal

This displays the message box with the Ok and Cancel button, the critical message icon, with the Ok button highlighted and the message box will display only when Excel is the active application.

MsgBox "Example 2", vbYesNo + vbQuestion + vbDefaultButton2 + vbSystemModal

This displays the message box with the Yes and No button, the warning query icon, with the No button highlighted and the message box will display in front of all applications.

Important: Each time we use the MsgBox function we can only select one of each:

  1. button type
  2. icon type
  3. default button
  4. modal type

In other words, we can only select one item from each of the first 4 groups.

The next section shows some more examples of using the message box.

VBA MsgBox Examples

The following examples show to display the various icons with the Yes and No buttons:

  ' Yes/No buttons with Critical icon and No button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbCritical)
 
 ' Yes/No buttons with Warning Query icon and Yes button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbQuestion)
 
 ' Yes/No buttons with Warning Message icon and Yes button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbExclamation)

 ' Yes/No button with Information Message icon and Cancel button selected
 resp = MsgBox("Do you wish to continue", vbYesNo + vbInformation)

The following examples show the Abort/Retry/Ignore button plus the help button with different buttons selected:

' Abort/Retry/Ignore button with the Help button displayed and Abort selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton1 + vbMsgBoxHelpButton)

' Abort/Retry/Ignore button with the help button displayed and Retry selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton2 + vbMsgBoxHelpButton)

' Abort/Retry/Ignore button with the Help button displayed and Ignore selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton3 + vbMsgBoxHelpButton)

' Abort/Retry/Ignore button with the Help button displayed and Help selected
resp = MsgBox("Error", vbAbortRetryIgnore + vbDefaultButton4 + vbMsgBoxHelpButton)

The following examples show some button selections and the title parameter being set:

' Retry/Cancel button with query warning as the icon and "Error" as the title
resp = MsgBox("An error occurred. Try again?", vbRetryCancel + vbQuestion, "Error")

' Ok button with critical icon and "System error" as the title
MsgBox "An error occurred", vbCritical, "System Error"

What’s Next?

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

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

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

Excel VBA Tutorial about how to create a message box with macrosIn this VBA Tutorial, you learn how to create message boxes and specify their most important characteristics, such as the following:

  1. How to specify the message displayed in the message box.
  2. How to customize or specify the buttons displayed by the message box.
  3. How to work with the value returned by the MsgBox function, and assign this value to a variable.
  4. How to specify the icon style used by the message box.
  5. How to specify the default button of in the message box.
  6. How to specify the modality of the message box.

This Excel VBA MsgBox 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 MsgBox Tutorial workbook example

Use the following Table of Contents to navigate to the section that interests you.

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:
    • Learn how to start working with macros here.
    • Learn about essential VBA terms here.
    • Learn how to enable or disable macros here.
    • Learn how to work with the VBE here.
    • Learn how to create and work with Sub procedures here.
    • Learn how to declare and work with variables here.
    • Learn about VBA data types here.
    • Learn how to work with functions in VBA here.
  • Practical VBA applications and macro examples:
    • Learn how to create UserForms here.

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

#1: Create MsgBox

VBA code to create MsgBox

To create a basic message box with VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString

Process to create MsgBox

To create a basic message box with VBA, use the MsgBox function (MsgBox …).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a basic message box using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.

Macro example to create MsgBox

The following macro example creates a basic message box with the message “Create Excel VBA MsgBox”.

Sub createMsgBox()
    'source: https://powerspreadsheets.com/
    'creates a message box
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box
    MsgBox Prompt:="Create Excel VBA MsgBox"

End Sub

Effects of executing macro example to create MsgBox

The following image illustrates the results of executing the macro example.

Macro creates MsgBox

#2: Create MsgBox with multiple lines (new line or line break)

VBA code to create MsgBox with multiple lines (new line or line break)

To create a message box with multiple lines (by including a new line or using line breaks) using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString1 & NewLineCharacter & PromptString2 & ... & NewLineCharacter & PromptString#

Process to create MsgBox with multiple lines (new line or line break)

To create a message box with multiple lines (by including a new line or using line breaks) using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify the message displayed in the message box as an appropriately concatenated (with the & character) combination of:
    • Strings (PromptString1, PromptString2, …, PromptString#); and
    • Characters that create a new line or line break (NewLineCharacter).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with multiple lines (by including a new line or using line breaks) using this statement structure:

      • The displayed message is that specified by the Prompt argument.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box.

      When you create a message box with multiple lines (by including a new line or using line breaks), you build the string expression assigned to Prompt (PromptString1 & NewLineCharacter & PromptString2 & … & NewLineCharacter & PromptString#) by concatenating as many strings (PromptString1, PromptString2, …, PromptString#) and newline characters (NewLineCharacter) as required.

      The maximum length of the string expression assigned to prompt is roughly 1024 characters. However, this maximum length may vary slightly depending on the width of the characters you include.

      If you explicitly declare a variable to represent this string expression, you can usually work with the String data type.

  3. Item: PromptString1, PromptString2, …, PromptString#.
    • VBA construct: Strings expressions.
    • Description: PromptStrings are the strings (excluding the new line characters) that determine the message displayed in the message box.

      If you explicitly declare variables to represent the different PromptStrings, you can usually work with the String data type.

  4. Item: &.
    • VBA construct: Concatenation (&) operator.
    • Description: The & operator carries out string concatenation. Therefore, & concatenates the different strings (PromptString1, PromptString2, …, PromptString#) and new line characters (NewLineCharacter) you use to specify the string expression assigned to the Prompt argument.
  5. Item: NewLineCharacter.
    • VBA construct: A character or character combination returning 1 of the following:
      • Carriage return.
      • Linefeed.
      • Carriage return linefeed combination.
      • New line (which is platform specific).
    • Description: 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 MsgBox with multiple lines (new line or line break)

The following macro example creates a message box with a message displayed in multiple lines by adding a new line as follows:

  • Line #1: “Create Excel VBA MsgBox”.
  • Line #2: “And add a new line”.
Sub MsgBoxNewLine()
    'source: https://powerspreadsheets.com/
    'creates a message box with a new line or line break
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with a new line or line break
    MsgBox Prompt:="Create Excel VBA MsgBox" & vbNewLine & "And add a new line"

End Sub

Effects of executing macro example to create MsgBox with multiple lines (new line or line break)

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box contains multiple lines.

Macro creates MsgBox with multiple lines

#3: Create MsgBox with title

VBA code to create MsgBox with title

To create a message box with title using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Title:=TitleString

Process to create MsgBox with title

To create a message box with title using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify the message displayed in the message box (Prompt:=PromptString).
  3. Specify the message box title (Title:=TitleString).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with title using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Title:=TitleString.
    • VBA construct: Title argument of the MsgBox function and string expression.
    • Description: Use the Title argument of the MsgBox function to specify the title displayed in the title bar of the message box. If you omit the Title argument, the title displayed in the title bar of the message box is “Microsoft Excel”.

      You generally specify TitleString as a string expression. If you explicitly declare a variable to represent TitleString, you can usually work with the String data type.

Macro example to create MsgBox with title

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The title “Add title to MsgBox.
Sub MsgBoxTitle()
    'source: https://powerspreadsheets.com/
    'creates a message box with a title
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with a title
    MsgBox Prompt:="Create Excel VBA MsgBox", Title:="Add title to MsgBox"

End Sub

Effects of executing macro example to create MsgBox with title

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box contains a custom title (Add title to MsgBox).

Macro creates MsgBox with title

#4: Create MsgBox that returns value based on user input and assigns value to a variable

VBA code to create MsgBox that returns value based on user input and assigns value to a variable

To create a message box that:

  • Returns a value based on the user’s input; and
  • Assigns that value to a variable;

with VBA, use a statement with the following structure:

Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression)

Process to create MsgBox that returns value based on user input and assigns value to a variable

To create a message box that:

  • Returns a value based on the user’s input; and
  • Assigns that value to a variable;

with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box (Buttons:=ButtonsExpression).
  3. Assign the value returned by the MsgBox function to a variable (Variable = MsgBox(…)).

VBA statement explanation

  1. Item: Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box that returns a value based on user input (and assigns the value to a variable) using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • Default button in the message box.
      • Modality of the message box.

      For these purposes, you can generally specify ButtonsExpression as a sum of the following 4 groups of values or built-in constants:

      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKOnly 0 Message box with only OK button
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the default button in the message box, as follows:
        Built-in constant Value Description
        vbDefaultButton1 0 Message box where first button is default button
        vbDefaultButton2 256 Message box where second button is default button
        vbDefaultButton3 512 Message box where third button is default button
        vbDefaultButton4 768 Message box where fourth button is default button

        For purposes of working with these different custom default button options, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression:

      • Specify ButtonsExpression as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 4 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems

      The default value of the Buttons argument is 0. Therefore, if you omit specifying the Buttons argument, the result is an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create MsgBox that returns value based on user input and assigns value to a variable

The following macro example does the following:

  1. Creates a message box that returns a value based on the user’s input.
  2. Assigns this value to a variable (myVariable = MsgBox(…)).
  3. Creates a second message box that displays the value held by variable.

The message box has the following characteristics:

  • Displays the message “Create Excel VBA MsgBox”.
  • Has 2 buttons: Yes and No (vbYesNo). The second button (vbDefaultButton2) is the default.
  • Displays an Information Message icon (vbInformation).
  • Is System modal (vbSystemModal).
Sub MsgBoxVariable()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box that returns a value, and (2) assigns value to a variable
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myVariable As Integer

    '(1) create a message box that returns a value, and (2) assign this value to a variable
    myVariable = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo + vbInformation + vbDefaultButton2 + vbSystemModal)

    'display message box with value held by variable
    MsgBox myVariable

End Sub

Effects of executing macro example to create MsgBox that returns value based on user input and assigns value to a variable

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box with the value returned by the MsgBox function and held by the variable.

Macro creates MsgBox that returns value

#5: Create MsgBox with OK button

VBA code to create MsgBox with OK button

To create a message box with an OK button using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbOKOnly

Process to create MsgBox with OK button

To create a message box with an OK button using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should display a single(OK) button (Buttons:=vbOKOnly).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with OK button using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbOKOnly.
    • VBA construct: Buttons argument of the MsgBox function and vbOKOnly built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbOKOnly (or 0) to explicitly specify that the message box has a single OK button.

      The default value of the Buttons argument is, anyway, 0. Therefore, if you omit specifying the Buttons argument, the result is also an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create MsgBox with OK button

The following macro example creates a message box with the message “Create Excel VBA MsgBox” and a single (OK) button (vbOKOnly).

Sub MsgBoxCustomButtonsOk()
    'source: https://powerspreadsheets.com/
    'creates a message box with an OK button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create message box with OK button
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbOKOnly

End Sub

Effects of executing macro example to create MsgBox with OK button

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box contains a single (OK) button.

Macro creates MsgBox with OK button

#6: Create MsgBox with OK and Cancel buttons

VBA code to create MsgBox with OK and Cancel buttons

To create a message box with OK and Cancel buttons using VBA, use a statement with the following structure:

OkCancelVariable = MsgBox(Prompt:=PromptString, Buttons:=vbOKCancel)

Process to create MsgBox with OK and Cancel buttons

To create a message box with OK and Cancel buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display OK and Cancel buttons (Buttons:=vbOKCancel).
  3. Assign the value returned by the MsgBox function to a variable (OkCancelVariable = MsgBox(…)).

VBA statement explanation

  1. Item: OkCancelVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare OkCancelVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to OkCancelVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with OK and Cancel buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 2 buttons: OK and Cancel.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        OK vbOK 1
        Cancel vbCancel 2

      If the user presses the Esc key, the MsgBox function returns vbCancel (or 2). In other words, pressing the Esc key is the equivalent to clicking the Cancel button.

  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbOKCancel.
    • VBA construct: Buttons argument of the MsgBox function and vbOKCancel built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbOKCancel (or 1) to specify that the message box has OK and Cancel buttons.

Macro example to create MsgBox with OK and Cancel buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • OK and Cancel buttons (vbOKCancel).
  2. Assigns the value returned by the MsgBox function to a variable (myOkCancelMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the OK button (If myOkCancelMsgBoxValue = vbOK), the macro creates a message box with the message “You clicked OK on the message box”.
    • If the user clicks the Cancel button (ElseIf myOkCancelMsgBoxValue = vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsOkCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with OK and Cancel buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myOkCancelMsgBoxValue As Integer

    '(1) create a message box with OK and Cancel buttons, and (2) assign value returned by message box to a variable
    myOkCancelMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbOKCancel)

    '(1) check which button was clicked (OK or Cancel), and (2) execute appropriate statements
    If myOkCancelMsgBoxValue = vbOK Then

        'display message box confirming that OK button was clicked
        MsgBox "You clicked OK on the message box"

    ElseIf myOkCancelMsgBoxValue = vbCancel Then

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

    End If

End Sub

Effects of executing macro example to create MsgBox with OK and Cancel buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (OK or Cancel).

Macro creates MsgBox with OK and Cancel buttons

#7: Create MsgBox with Yes and No buttons

VBA code to create MsgBox with Yes and No buttons

To create a message box with Yes and No buttons using VBA, use a statement with the following structure:

YesNoVariable = MsgBox(Prompt:=PromptString, Buttons:=vbYesNo)

Process to create MsgBox with Yes and No buttons

To create a message box with Yes and No buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Yes and No buttons (Buttons:=vbYesNo).
  3. Assign the value returned by the MsgBox function to a variable (YesNoVariable = MsgBox(…)).

VBA statement explanation

  1. Item: YesNoVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare YesNoVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to YesNoVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Yes and No buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 2 buttons: Yes and No.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Yes vbYes 6
        No vbNo 7
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbYesNo.
    • VBA construct: Buttons argument of the MsgBox function and vbYesNo built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbYesNo (or 4) to specify that the message box has Yes and No buttons.

Macro example to create MsgBox with Yes and No buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes and No buttons (vbYesNo).
  2. Assigns the value returned by the MsgBox function to a variable (myYesNoMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (If myYesNoMsgBoxValue = vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (ElseIf myYesNoMsgBoxValue = vbNo), the macro creates a message box with the message “You clicked No on the message box”.
Sub MsgBoxCustomButtonsYesNo()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes and No buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myYesNoMsgBoxValue As Integer

    '(1) create a message box with Yes and No buttons, and (2) assign value returned by message box to a variable
    myYesNoMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo)

    '(1) check which button was clicked (Yes or No), and (2) execute appropriate statements
    If myYesNoMsgBoxValue = vbYes Then

        'display message box confirming that Yes button was clicked
        MsgBox "You clicked Yes on the message box"

    ElseIf myYesNoMsgBoxValue = vbNo Then

        'display message box confirming that No button was clicked
        MsgBox "You clicked No on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox with Yes and No buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Yes or No).

Macro creates MsgBox with Yes and No buttons

#8: Create MsgBox with Yes, No and Cancel buttons

VBA code to create MsgBox with Yes, No and Cancel buttons

To create a message box with Yes, No and Cancel buttons using VBA, use a statement with the following structure:

YesNoCancelVariable = MsgBox(Prompt:=PromptString, Buttons:=vbYesNoCancel)

Process to create MsgBox with Yes, No and Cancel buttons

To create a message box with Yes, No and Cancel buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Yes, No and Cancel buttons (Buttons:=vbYesNoCancel).
  3. Assign the value returned by the MsgBox function to a variable (YesNoCancelVariable = MsgBox(…)).

VBA statement explanation

  1. Item: YesNoCancelVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare YesNoCancelVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to YesNoCancelVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Yes, No and Cancel buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 3 buttons: Yes, No and Cancel.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Cancel vbCancel 2
        Yes vbYes 6
        No vbNo 7

        If the user presses the Esc key, the MsgBox function returns vbCancel (or 2). In other words, pressing the Esc key is the equivalent to clicking the Cancel button.

  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbYesNoCancel.
    • VBA construct: Buttons argument of the MsgBox function and vbYesNoCancel built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbYesNoCancel (or 3) to specify that the message box has Yes, No and Cancel buttons.

Macro example to create MsgBox with Yes, No and Cancel buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes, No and Cancel buttons (vbYesNoCancel).
  2. Assigns the value returned by the MsgBox function to a variable (myYesNoCancelMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (Case vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (Case vbNo), the macro creates a message box with the message “You clicked No on the message box”.
    • If the user clicks the Cancel button (Case vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsYesNoCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes, No and Cancel buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myYesNoCancelMsgBoxValue As Integer

    '(1) create a message box with Yes, No and Cancel buttons, and (2) assign value returned by message box to a variable
    myYesNoCancelMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNoCancel)

    '(1) check which button was clicked (Yes, No or Cancel), and (2) execute appropriate statements
    Select Case myYesNoCancelMsgBoxValue

        'display message box confirming that Yes button was clicked
        Case vbYes: MsgBox "You clicked Yes on the message box"

        'display message box confirming that No button was clicked
        Case vbNo: MsgBox "You clicked No on the message box"

        'display message box confirming that Cancel button was clicked
        Case vbCancel: MsgBox "You clicked Cancel on the message box"

    End Select

End Sub

Effects of executing macro example to create MsgBox with Yes, No and Cancel buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Yes, No or Cancel).

Macro creates MsgBox with Yes, No and Cancel buttons

#9: Create MsgBox with Retry and Cancel buttons

VBA code to create MsgBox with Retry and Cancel buttons

To create a message box with Retry and Cancel buttons using VBA, use a statement with the following structure:

RetryCancelVariable = MsgBox(Prompt:=PromptString, Buttons:=vbRetryCancel)

Process to create MsgBox with Retry and Cancel buttons

To create a message box with Retry and Cancel buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Retry and Cancel buttons (Buttons:=vbRetryCancel).
  3. Assign the value returned by the MsgBox function to a variable (RetryCancelVariable = MsgBox(…)).

VBA statement explanation

  1. Item: RetryCancelVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare RetryCancelVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to RetryCancelVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Retry and Cancel buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 2 buttons: Retry and Cancel.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Cancel vbCancel 2
        Retry vbRetry 4

      If the user presses the Esc key, the MsgBox function returns vbCancel (or 2). In other words, pressing the Esc key is the equivalent to clicking the Cancel button.

  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbRetryCancel.
    • VBA construct: Buttons argument of the MsgBox function and vbRetryCancel built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbRetryCancel (or 5) to specify that the message box has Retry and Cancel buttons.

Macro example to create MsgBox with Retry and Cancel buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Retry and Cancel buttons (vbRetryCancel).
  2. Assigns the value returned by the MsgBox function to a variable (myRetryCancelMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Retry button (If myRetryCancelMsgBoxValue = vbRetry), the macro creates a message box with the message “You clicked Retry on the message box”.
    • If the user clicks the Cancel button (ElseIf myRetryCancelMsgBoxValue = vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsRetryCancel()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Retry and Cancel buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myRetryCancelMsgBoxValue As Integer

    '(1) create a message box with Retry and Cancel buttons, and (2) assign value returned by message box to a variable
    myRetryCancelMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbRetryCancel)

    '(1) check which button was clicked (Retry or Cancel), and (2) execute appropriate statements
    If myRetryCancelMsgBoxValue = vbRetry Then

        'display message box confirming that Retry button was clicked
        MsgBox "You clicked Retry on the message box"

    ElseIf myRetryCancelMsgBoxValue = vbCancel Then

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

    End If

End Sub

Effects of executing macro example to create MsgBox with Retry and Cancel buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Retry or Cancel).

Macro creates MsgBox with Retry and Cancel buttons

#10: Create MsgBox with Abort, Retry and Ignore buttons

VBA code to create MsgBox with Abort, Retry and Ignore buttons

To create a message box with Abort, Retry and Ignore buttons using VBA, use a statement with the following structure:

AbortRetryIgnoreVariable = MsgBox(Prompt:=PromptString, Buttons:=vbAbortRetryIgnore)

Process to create MsgBox with Abort, Retry and Ignore buttons

To create a message box with Abort, Retry and Ignore buttons using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify that the message box should display Abort, Retry and Ignore buttons (Buttons:=vbAbortRetryIgnore).
  3. Assign the value returned by the MsgBox function to a variable (AbortRetryIgnoreVariable = MsgBox(…)).

VBA statement explanation

  1. Item: AbortRetryIgnoreVariable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare AbortRetryIgnoreVariable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to AbortRetryIgnoreVariable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with Abort, Retry and Ignore buttons using this statement structure:

      • The displayed message is PromptString.
      • The message box contains 3 buttons: Abort, Retry and Ignore.
      • The value returned by the MsgBox function is 1 of the following:
        Button clicked by user Built-in constant Value
        Abort vbAbort 3
        Retry vbRetry 4
        Ignore vbIgnore 5
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=vbAbortRetryIgnore.
    • VBA construct: Buttons argument of the MsgBox function and vbAbortRetryIgnore built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbAbortRetryIgnore (or 2) to specify that the message box has Abort, Retry and Ignore buttons.

Macro example to create MsgBox with Abort, Retry and Ignore buttons

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Abort, Retry and Ignore buttons (vbAbortRetryIgnore).
  2. Assigns the value returned by the MsgBox function to a variable (myAbortRetryIgnoreMsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Abort button (Case vbAbort), the macro creates a message box with the message “You clicked Abort on the message box”.
    • If the user clicks the Retry button (Case vbRetry), the macro creates a message box with the message “You clicked Retry on the message box”.
    • If the user clicks the Ignore button (Case vbIgnore), the macro creates a message box with the message “You clicked Ignore on the message box”.
Sub MsgBoxCustomButtonsAbortRetryIgnore()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Abort, Retry and Ignore buttons, and (2) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myAbortRetryIgnoreMsgBoxValue As Integer

    '(1) create a message box with Yes, No and Cancel buttons, and (2) assign value returned by message box to a variable
    myAbortRetryIgnoreMsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbAbortRetryIgnore)

    '(1) check which button was clicked (Abort, Retry or Ignore), and (2) execute appropriate statements
    Select Case myAbortRetryIgnoreMsgBoxValue

        'display message box confirming that Abort button was clicked
        Case vbAbort: MsgBox "You clicked Abort on the message box"

        'display message box confirming that Retry button was clicked
        Case vbRetry: MsgBox "You clicked Retry on the message box"

        'display message box confirming that Ignore button was clicked
        Case vbIgnore: MsgBox "You clicked Ignore on the message box"

    End Select

End Sub

Effects of executing macro example to create MsgBox with Abort, Retry and Ignore buttons

The following image illustrates the results of executing the macro example. Notice that, as expected, the macro displays a second message box whose message depends on the clicked button (Abort, Retry or Ignore).

Macro creates MsgBox with Abort, Retry and Ignore buttons

#11: Create MsgBox with critical style

VBA code to create MsgBox with critical style

To create a message box with the critical icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbCritical

Process to create MsgBox with critical style

To create a message box with the critical icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the critical icon style (Buttons:=vbCritical).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with a critical icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbCritical.
    • VBA construct: Buttons argument of the MsgBox function and vbCritical built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbCritical (or 16) to specify that the message box uses the critical icon style and, therefore, displays a Critical Message icon.

Macro example to create MsgBox with critical style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The critical message icon style (vbCritical), which results in the Critical Message icon being displayed.
Sub MsgBoxCriticalStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with a critical message icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with a critical message icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbCritical

End Sub

Effects of executing macro example to create MsgBox with critical style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the critical message icon style.

Macro creates MsgBox with critical style icon

#12: Create MsgBox with question style

VBA code to create MsgBox with question style

To create a message box with the question icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbQuestion

Process to create MsgBox with question style

To create a message box with the question icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the question icon style (Buttons:=vbQuestion).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with the question icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbQuestion.
    • VBA construct: Buttons argument of the MsgBox function and vbQuestion built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbQuestion (or 32) to specify that the message box uses the question icon style and, therefore, displays a Warning Query icon.

Macro example to create MsgBox with question style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The question icon style (vbQuestion), which results in the Warning Query icon being displayed.
Sub MsgBoxQuestionStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with the question icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with the question icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbQuestion

End Sub

Effects of executing macro example to create MsgBox with question style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the question icon style.

Macro creates MsgBox with question style icon

#13: Create MsgBox with exclamation style

VBA code to create MsgBox with exclamation style

To create a message box with the exclamation icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbExclamation

Process to create MsgBox with exclamation style

To create a message box with the exclamation icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the exclamation icon style (Buttons:=vbExclamation).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with an exclamation icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbExclamation.
    • VBA construct: Buttons argument of the MsgBox function and vbExclamation built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbExclamation (or 48) to specify that the message box uses the exclamation icon style and, therefore, displays a Warning Message icon.

Macro example to create MsgBox with exclamation style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The exclamation icon style (vbExclamation), which results in the Warning Message icon being displayed.
Sub MsgBoxExclamationStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with a warning message icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with an exclamation icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbExclamation

End Sub

Effects of executing macro example to create MsgBox with exclamation style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the exclamation icon style.

Macro creates MsgBox with exclamation style icon

#14: Create MsgBox with information style

VBA code to create MsgBox with information style

To create a message box with the information icon style using VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbInformation

Process to create MsgBox with information style

To create a message box with the information icon style using VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should use the information icon style (Buttons:=vbInformation).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box with an information icon style using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbInformation.
    • VBA construct: Buttons argument of the MsgBox function and vbInformation built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbInformation (or 64) to specify that the message box uses the information icon style and, therefore, displays an Information Message icon.

Macro example to create MsgBox with information style

The following macro example creates a message box with:

  • The message “Create Excel VBA MsgBox”; and
  • The information icon style (vbInformation), which results in the Information Message icon being displayed.
Sub MsgBoxInformationStyle()
    'source: https://powerspreadsheets.com/
    'creates a message box with an information message icon style
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a message box with an information message icon style
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbInformation

End Sub

Effects of executing macro example to create MsgBox with information style

The following image illustrates the results of executing the macro example. Notice that, as expected, the message box uses the information message icon style.

Macro creates MsgBox with information style icon

#15: Create MsgBox where first button is default

VBA code to create MsgBox where first button is default

To create a message box where the first button is the default with VBA, use a statement with the following structure:

CustomButtons1Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression1 + vbDefaultButton1)

Process to create MsgBox where first button is default

To create a message box where the first button is the default with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box and, explicitly, specify that the first button is the default one (Buttons:=ButtonsExpression1 + vbDefaultButton1).
  3. Assign the value returned by the MsgBox function to a variable (CustomButtons1Variable = MsgBox(…)).

VBA statement explanation

  1. Item: CustomButtons1Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare CustomButtons1Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to CustomButtons1Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box where the first button is the default using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression1. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression1 + vbDefaultButton1.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • That the first button in the message box is the default.
      • Modality of the message box.
  6. Item: ButtonsExpression1.
    • VBA construct: Numeric expression partially specifying the value assigned to the Buttons argument.
    • Description: Specify ButtonsExpression1 as a sum of the following 3 groups of values or built-in constants:
      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKOnly 0 Message box with only OK button
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression1:

      • Specify ButtonsExpression1 as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 3 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems
  7. Item: vbDefaultButton1.
    • VBA construct: vbDefaultButton1 built-in constant.
    • Description: Include vbDefaultButton1 (or 0) in the numeric expression assigned to the Buttons argument to specify that the first button of the message box is the default button.

      The default value of the Buttons argument is, anyway, 0. Therefore, if you omit specifying the Buttons argument, the result is an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create MsgBox where first button is default

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes and No buttons (vbYesNo). The first button (vbDefaultButton1) is explicitly set as the default.
  2. Assigns the value returned by the MsgBox function to a variable (myCustomButtonsDefault1MsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (If myCustomButtonsDefault1MsgBoxValue = vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (ElseIf myCustomButtonsDefault1MsgBoxValue = vbNo), the macro creates a message box with the message “You clicked No on the message box”.
Sub MsgBoxCustomButtonsDefault1()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes and No buttons, (2) specifies that first button (Yes) is default, and (3) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myCustomButtonsDefault1MsgBoxValue As Integer

    '(1) create a message box with Yes and No buttons where the first button (Yes) is the default, and (2) assign value returned by message box to a variable
    myCustomButtonsDefault1MsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo + vbDefaultButton1)

    '(1) check which button was clicked (Yes or No), and (2) execute appropriate statements
    If myCustomButtonsDefault1MsgBoxValue = vbYes Then

        'display message box confirming that Yes button was clicked
        MsgBox "You clicked Yes on the message box"

    ElseIf myCustomButtonsDefault1MsgBoxValue = vbNo Then

        'display message box confirming that No button was clicked
        MsgBox "You clicked No on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox where first button is default

The following image illustrates the results of executing the macro example. Notice that, as expected, the first button in the message box is the default.

Macro creates MsgBox where first button is default

#16: Create MsgBox where second button is default

VBA code to create MsgBox where second button is default

To create a message box where the second button is the default with VBA, use a statement with the following structure:

CustomButtons2Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression1 + vbDefaultButton2)

Process to create MsgBox where second button is default

To create a message box where the second button is the default with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box and, explicitly, specify that the second button is the default one (Buttons:=ButtonsExpression1 + vbDefaultButton2).
  3. Assign the value returned by the MsgBox function to a variable (CustomButtons2Variable = MsgBox(…)).

VBA statement explanation

  1. Item: CustomButtons2Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare CustomButtons2Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to CustomButtons2Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box where the second button is the default using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression1. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression1 + vbDefaultButton2.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • That the second button in the message box is the default.
      • Modality of the message box.
  6. Item: ButtonsExpression1.
    • VBA construct: Numeric expression partially specifying the value assigned to the Buttons argument.
    • Description: Specify ButtonsExpression1 as a sum of the following 3 groups of values or built-in constants:
      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKOnly 0 Message box with only OK button
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        Usually, when creating a message box where the second button is the default, you don’t work with vbOKOnly (0). For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression1:

      • Specify ButtonsExpression1 as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 3 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems
  7. Item: vbDefaultButton2.
    • VBA construct: vbDefaultButton2 built-in constant.
    • Description: Include vbDefaultButton2 (or 256) in the numeric expression assigned to the Buttons argument to specify that the second button of the message box is the default button.

Macro example to create MsgBox where second button is default

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes and No buttons (vbYesNo). The second button (vbDefaultButton2) is set as the default.
  2. Assigns the value returned by the MsgBox function to a variable (myCustomButtonsDefault2MsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (If myCustomButtonsDefault2MsgBoxValue = vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (ElseIf myCustomButtonsDefault2MsgBoxValue = vbNo), the macro creates a message box with the message “You clicked No on the message box”.
Sub MsgBoxCustomButtonsDefault2()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes and No buttons, (2) specifies that second button (No) is default, and (3) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myCustomButtonsDefault2MsgBoxValue As Integer

    '(1) create a message box with Yes and No buttons where the second button (No) is the default, and (2) assign value returned by message box to a variable
    myCustomButtonsDefault2MsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNo + vbDefaultButton2)

    '(1) check which button was clicked (Yes or No), and (2) execute appropriate statements
    If myCustomButtonsDefault2MsgBoxValue = vbYes Then

        'display message box confirming that Yes button was clicked
        MsgBox "You clicked Yes on the message box"

    ElseIf myCustomButtonsDefault2MsgBoxValue = vbNo Then

        'display message box confirming that No button was clicked
        MsgBox "You clicked No on the message box"

    End If

End Sub

Effects of executing macro example to create MsgBox where second button is default

The following image illustrates the results of executing the macro example. Notice that, as expected, the second button in the message box is the default.

Macro creates MsgBox where second button is default

#17: Create MsgBox where third button is default

VBA code to create MsgBox where third button is default

To create a message box where the third button is the default with VBA, use a statement with the following structure:

CustomButtons3Variable = MsgBox(Prompt:=PromptString, Buttons:=ButtonsExpression + vbDefaultButton3)

Process to create MsgBox where third button is default

To create a message box where the third button is the default with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox(…)).
  2. Specify the buttons to be displayed in the message box and, explicitly, specify that the third button is the default one (Buttons:=ButtonsExpression1 + vbDefaultButton3).
  3. Assign the value returned by the MsgBox function to a variable (CustomButtons3Variable = MsgBox(…)).

VBA statement explanation

  1. Item: CustomButtons3Variable.
    • VBA construct: Variable.
    • Description: Variable you want to hold the value returned by the MsgBox function.

      If you explicitly declare CustomButtons3Variable, you can usually work with the Integer data type.

  2. Item: =.
    • VBA construct: Assignment (=) operator.
    • Description: The = operator assigns the Integer value returned by the MsgBox function to CustomButtons3Variable.
  3. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a message box where the third button is the default using this statement structure:

      • The displayed message is PromptString.
      • The message box contains the buttons specified by ButtonsExpression1. For purposes of working with the main custom button layouts, please refer to the appropriate sections of this Tutorial.
  4. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  5. Item: Buttons:=ButtonsExpression1 + vbDefaultButton3.
    • VBA construct: Buttons argument of the MsgBox function.
    • Description: Use the Buttons argument of the MsgBox function to specify the following:
      • Number and type of buttons displayed in the message box.
      • Icon style for the message box.
      • That the third button in the message box is the default.
      • Modality of the message box.
  6. Item: ButtonsExpression1.
    • VBA construct: Numeric expression partially specifying the value assigned to the Buttons argument.
    • Description: Specify ButtonsExpression1 as a sum of the following 3 groups of values or built-in constants:
      • Values or built-in constants that specify the number and type of buttons displayed in the message box, as follows:
        Built-in constant Value Description
        vbOKCancel 1 Message box with OK and Cancel buttons
        vbAbortRetryIgnore 2 Message box with Abort, Retry and Ignore buttons
        vbYesNoCancel 3 Message box with Yes, No and Cancel buttons
        vbYesNo 4 Message box with Yes and No buttons
        vbRetryCancel 5 Message box with Retry and Cancel buttons

        Usually, when creating a message box where the third button is the default, you work with either vbAbortRetryIgnore (2) or vbYesNoCancel (3). For purposes of working with these different custom button layouts, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the icon style of the message box, as follows:
        Built-in constant Value Description
        vbCritical 16 Message box with Critical Message icon
        vbQuestion 32 Message box with Warning Query icon
        vbExclamation 48 Message box with Warning Message icon
        vbInformation 64 Message box with Information Message icon

        For purposes of working with these different icon styles, please refer to the appropriate sections of this Tutorial.

      • Values or built-in constants that specify the modality of the message box, as follows:
        Built-in constant Value Description
        vbApplicationModal 0 Application modal message box
        vbSystemModal 4096 System modal message box

        For purposes of working with this different modality options, please refer to the appropriate sections of this Tutorial.

      When specifying ButtonsExpression1:

      • Specify ButtonsExpression1 as a sum of the applicable values or built-in constants.
      • Omit the values from the groups you don’t specify.
      • Use a maximum of 1 value from each of these 3 groups.
      • In addition to the values and built-in constants I list above, the Buttons argument accepts the following 4 settings:
        Built-in constant Value Description
        vbMsgBoxHelpButton 16384 Message box with an additional Help button.

        The MsgBox function also accepts a (optional) helpfile and context arguments that specify the applicable Help file and Help context number.

        Clicking on the Help button results in the applicable help being provided. The MsgBox function only returns a value when the user clicks 1 of the other buttons in the message box.

        vbMsgBoxSetForeground 65536 Message box is the foreground window
        vbMsgBoxRight 524288 Text within the message box is aligned to the right
        vbMsgBoxRtlReading 1048576 Text within the message box is displayed as right-to-left reading on Hebrew and Arabic systems
  7. Item: vbDefaultButton3.
    • VBA construct: vbDefaultButton3 built-in constant.
    • Description: Include vbDefaultButton3 (or 512) in the numeric expression assigned to the Buttons argument to specify that the third button of the message box is the default button.

Macro example to create MsgBox where third button is default

The following macro example does the following:

  1. Creates a message box with:
    • The message “Create Excel VBA MsgBox”; and
    • Yes, No and Cancel buttons (vbYesNoCancel). The third button (vbDefaultButton3) is set as the default.
  2. Assigns the value returned by the MsgBox function to a variable (myCustomButtonsDefault3MsgBoxValue).
  3. Checks which value was clicked by the user:
    • If the user clicks the Yes button (Case vbYes), the macro creates a message box with the message “You clicked Yes on the message box”.
    • If the user clicks the No button (Case vbNo), the macro creates a message box with the message “You clicked No on the message box”.
    • If the user clicks the Cancel button (Case vbCancel), the macro creates a message box with the message “You clicked Cancel on the message box”.
Sub MsgBoxCustomButtonsDefault3()
    'source: https://powerspreadsheets.com/
    '(1) creates a message box with Yes, No and Cancel buttons, (2) specifies that third button (Cancel) is default, and (3) executes certain statements depending on clicked button
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'declare variable to hold value returned by message box
    Dim myCustomButtonsDefault3MsgBoxValue As Integer

    '(1) create a message box with Yes, No and Cancel buttons where the third button (Cancel) is the default, and (2) assign value returned by message box to a variable
    myCustomButtonsDefault3MsgBoxValue = MsgBox(Prompt:="Create Excel VBA MsgBox", Buttons:=vbYesNoCancel + vbDefaultButton3)

    '(1) check which button was clicked (Yes, No or Cancel), and (2) execute appropriate statements
    Select Case myCustomButtonsDefault3MsgBoxValue

        'display message box confirming that Yes button was clicked
        Case vbYes: MsgBox "You clicked Yes on the message box"

        'display message box confirming that No button was clicked
        Case vbNo: MsgBox "You clicked No on the message box"

        'display message box confirming that Cancel button was clicked
        Case vbCancel: MsgBox "You clicked Cancel on the message box"

    End Select

End Sub

Effects of executing macro example to create MsgBox where third button is default

The following image illustrates the results of executing the macro example. Notice that, as expected, the third button in the message box is the default.

Macro creates MsgBox where third button is default

#18: Create Application modal MsgBox

VBA code to create Application modal MsgBox

To create an Application modal message box with VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbApplicationModal

Process to create Application modal MsgBox

To create an Application modal message box with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should be Application modal (Buttons:=vbApplicationModal).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create an Application modal message box using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbApplicationModal.
    • VBA construct: Buttons argument of the MsgBox function and vbApplicationModal built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbApplicationModal (or 0) to specify that the message box is Application modal. When a message box is Application modal, the user must respond to the message box prior to working again with the Excel Application.

      The default value of the Buttons argument is, anyway, 0. Therefore, if you omit specifying the Buttons argument, the result is also an Application modal message box with a single button (OK), which is also the default button, and no special icon style.

Macro example to create Application modal MsgBox

The following macro example creates an Application modal (vbApplicationModal) message box with the message “Create Excel VBA MsgBox”.

Sub MsgBoxApplicationModal()
    'source: https://powerspreadsheets.com/
    'creates an Application modal message box
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create an Application modal message box
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbApplicationModal

End Sub

Effects of executing macro example to create Application modal MsgBox

The following image illustrates the results of executing the macro example. This message box is Application modal.

Macro creates Application modal MsgBox

#19: Create System modal MsgBox

VBA code to create System modal MsgBox

To create a System modal message box with VBA, use a statement with the following structure:

MsgBox Prompt:=PromptString, Buttons:=vbSystemModal

Process to create System modal MsgBox

To create a System modal message box with VBA, follow these steps:

  1. Create a message box with the MsgBox function (MsgBox …).
  2. Specify that the message box should be System modal (Buttons:=vbSystemModal).

VBA statement explanation

  1. Item: MsgBox.
    • VBA construct: MsgBox function.
    • Description: The MsgBox function does the following:
      • Displays a message in a message box.
      • Waits for the user to click a button.
      • Returns a value of the Integer data type. This value indicates the button of the message box clicked by the user.

      When you create a System modal message box using this statement structure:

      • The displayed message is PromptString.
      • The message box contains a single button: OK. For purposes of including other custom button layouts, please refer to the appropriate sections of this Tutorial.
      • The value returned by the MsgBox function is vbOK (or 1). For purposes of assigning the value returned by the MsgBox function to a variable, please refer to the appropriate section of this Tutorial.
  2. Item: Prompt:=PromptString.
    • VBA construct: Prompt argument of the MsgBox function and string expression.
    • Description: Use the Prompt argument of the MsgBox function to specify the message displayed in the message box. For these purposes:
      • You generally specify PromptString as a string expression.
      • If you explicitly declare a variable to represent PromptString, you can usually work with the String data type.
      • 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. For purposes of creating a message box with multiple lines (by including line breaks or new lines), please refer to the appropriate section of this Tutorial.
  3. Item: Buttons:=vbSystemModal.
    • VBA construct: Buttons argument of the MsgBox function and vbSystemModal built-in constant.
    • Description: Set the Buttons argument of the MsgBox function to vbSystemModal (or 4096) to specify that the message box is System modal. When a message box is System modal, the user must respond to the message box prior to working with any application.

Macro example to create System modal MsgBox

The following macro example creates a System modal (vbSystemModal) message box with the message “Create Excel VBA MsgBox”.

Sub MsgBoxSystemModal()
    'source: https://powerspreadsheets.com/
    'creates a System modal message box
    'for further information: https://powerspreadsheets.com/excel-vba-msgbox/

    'create a System modal message box
    MsgBox Prompt:="Create Excel VBA MsgBox", Buttons:=vbSystemModal

End Sub

Effects of executing macro example to create System modal MsgBox

The following image illustrates the results of executing the macro example. This message box is System modal.

Macro creates System modal MsgBox

Learn more about creating message boxes with VBA

Workbook example used in this Excel VBA MsgBox Tutorial

You can get immediate free access to the example workbook that accompanies this Excel VBA MsgBox Tutorial by clicking the button below.

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

Понравилась статья? Поделить с друзьями:

А вот еще интересные статьи:

  • Excel vba время выполнения макроса
  • Excel vba внести данные в ячейку
  • Excel vba включить фильтр
  • Excel vba виды модулей
  • Excel vba видимость переменных

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии