Запрос в VBA «Да», «Нет» |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
In this Article
- VBA MsgBox Function
- VBA YesNo Message Box
- VBA Message Box Options
- Syntax of MsgBox Function
- Customize Message Box Title and Prompt
- MessageBox LineBreaks
- MsgBox Icons
- MsgBox Icons – Information
- MsgBox Icons – Critical
- MsgBox Icons – Question
- MsgBox Icons – Exclamation
- MsgBox Variables
- OK Message Box – vbOKOnly
- OK Cancel Message Box – vbOKCancel
- Yes No Message Box – vbYesNo
- Yes No Cancel Message Box – vbYesNoCancel
- Abort Retry Ignore Message Box – vbAbortRetryIgnore
- Retry Cancel Message Box – vbRetryCancel
- VBA MessageBox Examples
- Message Box Confirmation Before Running Macro
- Yes / No Message Box – Exit Sub
- VBA Message Box in Access VBA
This tutorial will cover how to use the VBA MsgBox Function to display messageboxes to users (including the YesNo Messagebox). You might also be interested in our article on InputBoxes.
VBA MsgBox Function
In VBA, it’s easy to display a simple MsgBox:
MsgBox "This is a Message Box"
However you can do a lot more than display a simple OK message box. Let’s quickly look at complicated example before we dive into specifics…
VBA YesNo Message Box
Below we will create a message box with:
- A title “Message Box Title” and prompt “Text”
- A question mark icon
- Yes / No options instead of a simple “OK”
- Default button = ‘No’
Dim answer As Integer
answer = MsgBox("Text", vbQuestion + vbYesNo + vbDefaultButton2, "Message Box Title")
The messagebox will return vbYes or vbNo depending on the user’s choice. You can then then perform different actions based on the choice:
If answer = vbYes Then
MsgBox "Yes"
Else
MsgBox "No"
End If
In the next section we will show you all of the options available to you when creating message boxes. Then we will introduce you to the syntax of the MsgBox Function and finally go over other message box examples.
VBA Message Box Options
Take a look at the image below. Here you will see (almost) all of the options available to you when creating message boxes. Take notice of the icons and the different buttons.
This is a screenshot of the “MessageBox Builder” from our Premium VBA Add-in: AutoMacro. The MessageBox Builder allows you to quickly design your desired messagebox and insert the code into your code module. It also contains many other code builders, an extensive VBA code library, and an assortment of coding tools. It’s a must-have for any VBA developer.
Syntax of MsgBox Function
MsgBox( prompt [, buttons ] [, title ] [, helpfile, context ] )
prompt (Required) – This is the primary message box text.
buttons – Choose which buttons to display. If omitted, ‘OKonly’. Here you can also specify what icon to show and the default button.
title – The title at the top of the message box. If omitted, the name of the current application is displayed (ex. Microsoft Excel).
helpfile – Specify help file that can be accessed when user clicks on the ‘Help’ button. If specified, then you must also add context (below)
context – Numeric expression representing the Help context number assigned to the appropriate Help topic.
You can probably ignore the helpfile and context arguments. I’ve never seen them used.
Customize Message Box Title and Prompt
The MsgBox function allows you to customize the title and prompt messages like so:
Msgbox "Prompt",,"Title"
Another example:
Sub MsgBoxPromptTitle()
MsgBox "Step 1 Complete. Click OK to run step 2.",, "Step 1 of 5"
End Sub
Important! You must remember to surround your text with quotations.
MessageBox LineBreaks
You can also add line breaks to your message box prompts with ‘vbNewLine’.
Sub MsgBoxPromptTitle_NewLine()
MsgBox "Step 1 Complete." & vbNewLine & "Click OK to Run Step 2.", , "Step 1 of 5"
End Sub
Notice we use the & symbol to join text together. You can learn more about using & with text and other options for inserting linebreaks in our article on joining text.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
MsgBox Icons
VBA gives you the ability to add one of four pre-built icons to your message boxes:
Icon Constant | Icon |
---|---|
vbInformation | |
vbCritical | |
vbQuestion | |
vbExclamation |
The Icon constant should be placed within the button argument:
Sub MsgBoxQuestionIcon()
MsgBox "Question Example", vbQuestion
End Sub
This will generate the default ‘OK’ message box with the Question icon:
Notice how when you type, the VBA Editor will show you the options available to you:
This is helpful because you don’t need to remember the exact syntax or names of icons or buttons.
Now we will demo each message box icon:
MsgBox Icons – Information
Sub MsgBoxInformationIcon()
MsgBox "Information Example", vbInformation
End Sub
MsgBox Icons – Critical
Sub MsgBoxCriticalIcon()
MsgBox "Critical Example", vbCritical
End Sub
VBA Programming | Code Generator does work for you!
MsgBox Icons – Question
Sub MsgBoxQuestionIcon()
MsgBox "Question Example", vbQuestion
End Sub
MsgBox Icons – Exclamation
Sub MsgBoxExclamationIcon()
MsgBox "Exclamation Example", vbExclamation
End Sub
Below we will talk about generating message boxes with different button layouts. If you do choose a different message box type, you will need to append the icon type after the buttons using a “+”:
Sub MsgBoxQuestionIcon()
MsgBox "Do you want to continue?", vbOKCancel + vbQuestion
End Sub
MsgBox Variables
So far we have worked primarily with the default ‘OK’ message box. The OK message box only has one option: Pressing ‘OK’ allows the code to continue. However, you can also specify other button groupings: OK / Cancel, Yes / No, etc.
In which case you will want to perform different actions based on which button is pressed. Let’s look at an example.
Here is the message box we will generate:
This is the entire code (we will break it down next):
Sub MsgBoxVariable()
Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)
If answer = vbYes Then
MsgBox "Yes"
Else
MsgBox "No"
End If
End Sub
First we assign the messagebox output to an integer variable.
Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)
Next we use an If-Else to determine what to do based on which button is pressed:
If answer = vbYes Then
MsgBox "Yes"
Else
MsgBox "No"
End If
The MsgBox function returns an integer value (between 1-7) so we define the variable as an integer type. However, instead of referring to the integer number, you can refer to a constant (ex. vbOK, vbCancel, etc.). Look at this table to see all of the options:
Button | Constant | Value |
---|---|---|
OK | vbOK | 1 |
Cancel | vbCancel | 2 |
Abort | vbAbort | 3 |
Retry | vbRetry | 4 |
Ignore | vbIgnore | 5 |
Yes | vbYes | 6 |
No | vbNo | 7 |
Now we will demo each button grouping:
OK Message Box – vbOKOnly
This is the standard VBA messagebox.
Sub MsgBox_OKOnly()
Dim answer As Integer
answer = MsgBox("OKOnly Example", vbOKOnly)
End Sub
OK Cancel Message Box – vbOKCancel
Sub MsgBox_OKCancel()
Dim answer As Integer
answer = MsgBox("OK Cancel Example", vbOKCancel)
If answer = vbOK Then
MsgBox "OK"
Else
MsgBox "Cancel"
End If
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Yes No Message Box – vbYesNo
Sub MsgBox_YesNo()
Dim answer As Integer
answer = MsgBox("Yes No Example", vbYesNo)
If answer = vbYes Then
MsgBox "Yes"
Else
MsgBox "No"
End If
End Sub
Yes No Cancel Message Box – vbYesNoCancel
Sub MsgBox_YesNoCancel()
Dim answer As Integer
answer = MsgBox("Yes No Cancel Example", vbYesNoCancel)
If answer = vbYes Then
MsgBox "Yes"
ElseIf answer = vbNo Then
MsgBox "No"
Else
MsgBox "Cancel"
End If
End Sub
Abort Retry Ignore Message Box – vbAbortRetryIgnore
Sub MsgBox_AbortRetryIgnore()
Dim answer As Integer
answer = MsgBox("Abort Retry Ignore Example", vbAbortRetryIgnore)
If answer = vbAbort Then
MsgBox "Abort"
ElseIf answer = vbRetry Then
MsgBox "Retry"
Else
MsgBox "Ignore"
End If
End Sub
Retry Cancel Message Box – vbRetryCancel
Sub MsgBox_RetryCancel()
Dim answer As Integer
answer = MsgBox("Retry Cancel Example", vbRetryCancel)
If answer = vbRetry Then
MsgBox "Retry"
Else
MsgBox "Cancel"
End If
End Sub
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
VBA MessageBox Examples
Message Box Confirmation Before Running Macro
This code will display a Yes No Message box before calling a macro. If Yes is clicked the macro is called, if No is clicked, the Macro does not run.
Sub Msgbox_BeforeRunning()
Dim answer As Integer
answer = MsgBox("Do you want to run Macro1?", vbQuestion + vbYesNo)
If answer = vbYes Then Call Macro1
End Sub
Yes / No Message Box – Exit Sub
Here we will confirm with the user whether to continue running a macro. If No is clicked, the code will exit the sub, otherwise the procedure will continue.
Sub Msgbox_BeforeRunning()
Dim answer As Integer
answer = MsgBox("Do you want to continue?", vbQuestion + vbYesNo)
If answer = vbNo Then Exit Sub
'Some Code
End Sub
VBA Message Box in Access VBA
All of the above examples work exactly the same in Access VBA as in Excel VBA.
В Excel вы можете напрямую запустить макрос, нажав клавишу F5 ключ или щелкните Run в Microsoft Visual Basic для приложений окно. Но иногда вам может понадобиться создать окно сообщения, которое спросит пользователя, хочет ли он запустить макрос. Если да, то продолжайте выполнение кода, если нет, прекратите выполнение кода. В этой статье я расскажу о том, как создать окно сообщения «да нет» перед запуском макроса в Excel.
Перед запуском макроса с кодом VBA создайте окно сообщения да нет
Перед запуском макроса с кодом VBA создайте окно сообщения да нет
Следующий код VBA может помочь вам добавить поле запроса да нет, чтобы подтвердить, запущен ли макрос, выполните следующие действия:
1. Удерживайте ALT + F11 , чтобы открыть Microsoft Visual Basic для приложений окно.
2. Нажмите Вставить > Модули, и вставьте следующий макрос в Модули Окно.
Код VBA: создайте окно сообщения да нет перед запуском макроса:
Sub continue()
CarryOn = MsgBox("Do you want to run this macro?", vbYesNo, "Kutools for Excel")
If CarryOn = vbYes Then
'put rest of code here
End If
End Sub
Внимание: В приведенном выше коде скопируйте и вставьте свой собственный код без ниже заголовок и End Sub нижний колонтитул между Если CarryOn = vbYes, то и конец, если скрипты. Смотрите скриншот:
3, Затем нажмите F5 key, появится окно с напоминанием о том, что вы хотите запустить этот код, нажмите Да кнопку, чтобы продолжить, и нажмите Нет чтобы остановиться, см. снимок экрана :
Лучшие инструменты для работы в офисе
Kutools for Excel Решит большинство ваших проблем и повысит вашу производительность на 80%
- Снова использовать: Быстро вставить сложные формулы, диаграммы и все, что вы использовали раньше; Зашифровать ячейки с паролем; Создать список рассылки и отправлять электронные письма …
- Бар Супер Формулы (легко редактировать несколько строк текста и формул); Макет для чтения (легко читать и редактировать большое количество ячеек); Вставить в отфильтрованный диапазон…
- Объединить ячейки / строки / столбцы без потери данных; Разделить содержимое ячеек; Объединить повторяющиеся строки / столбцы… Предотвращение дублирования ячеек; Сравнить диапазоны…
- Выберите Дубликат или Уникальный Ряды; Выбрать пустые строки (все ячейки пустые); Супер находка и нечеткая находка во многих рабочих тетрадях; Случайный выбор …
- Точная копия Несколько ячеек без изменения ссылки на формулу; Автоматическое создание ссылок на несколько листов; Вставить пули, Флажки и многое другое …
- Извлечь текст, Добавить текст, Удалить по позиции, Удалить пробел; Создание и печать промежуточных итогов по страницам; Преобразование содержимого ячеек в комментарии…
- Суперфильтр (сохранять и применять схемы фильтров к другим листам); Расширенная сортировка по месяцам / неделям / дням, периодичности и др .; Специальный фильтр жирным, курсивом …
- Комбинируйте книги и рабочие листы; Объединить таблицы на основе ключевых столбцов; Разделить данные на несколько листов; Пакетное преобразование xls, xlsx и PDF…
- Более 300 мощных функций. Поддерживает Office/Excel 2007-2021 и 365. Поддерживает все языки. Простое развертывание на вашем предприятии или в организации. Полнофункциональная 30-дневная бесплатная пробная версия. 60-дневная гарантия возврата денег.
Вкладка Office: интерфейс с вкладками в Office и упрощение работы
- Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
- Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
- Повышает вашу продуктивность на 50% и сокращает количество щелчков мышью на сотни каждый день!
Комментарии (1)
Оценок пока нет. Оцените первым!
You can use the following syntax in VBA to create a message box that allows a user to select Yes or No:
Sub MsgBoxYesNo()
'ask user if they want to multiply two cells
UserResponse = MsgBox("Do you want to multiply cells A1 and B1?", vbYesNo)
'perform action based on user response
If UserResponse = vbYes Then
Range("C1") = Range("A1") * Range("B1")
Else
MsgBox "No Multiplication was Performed"
End If
End Sub
This particular macro creates a message box that asks the user if they want to multiply cells A1 and B1.
If the user clicks “Yes” then the two cells are multiplied and the result is shown in cell C1.
If the user clicks “No” then a new message box appears that tells the them no multiplication was performed.
Note that the statement vbYesNo is what inserts “Yes” and “No” buttons for the user to click.
The following examples shows how to use this syntax in practice.
Suppose we have the following two values in cells A1 and B1 in our Excel sheet:
Suppose we would like to create a macro that shows a message box to the user and asks them whether they’d like to multiply the values in cells A1 and B1 or not.
We can create the following macro to do so:
Sub MsgBoxYesNo()
'ask user if they want to multiply two cells
UserResponse = MsgBox("Do you want to multiply cells A1 and B1?", vbYesNo)
'perform action based on user response
If UserResponse = vbYes Then
Range("C1") = Range("A1") * Range("B1")
Else
MsgBox "No Multiplication was Performed"
End If
End Sub
When we run this macro, the following message box appears:
If we click Yes, then the macro will multiply the values in cells A1 and B2 and display the result in cell C1:
However, if we click No then a new message box will appear:
The message box tells us that no multiplication was performed since we clicked No in the previous message box.
Additional Resources
The following tutorials explain how to perform other common tasks in VBA:
VBA: How to Add New Line to Message Box
VBA: How to Add New Sheets
VBA: How to Freeze Panes
In VBA, using the message box, we can create a yes no msgbox, used to record user input based on clicking yes or no. The syntax to make a yes-no message box is as follows variable = MsgBox(“Text”, vbQuestion + vbYesNo + vbDefaultButton2, “Message Box Title”) where one must declare variable as an integer.
In VBA coding, we often need to collect the input values from the users to perform some tasks. One of such tasks is collecting the users’ yes or no responses. By using VBA MsgBox Yes No method, we can write the code to proceed further in the code.
In certain situations, we may need to present a “Yes” or “No” option in front of the user to give their response based on them. Then, we can run the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.
For example, look at the below image of the MsgBox in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.
If the user says Yes, “we can write code to perform a specific task,” and if the user says “No,” we can write code to perform another set of tasks.
Table of contents
- Excel VBA MsgBox (Yes/No)
- How to Work with MsgBox Yes/No Response?
- Example #1 – Copy and Paste based on Response
- Example #2 – Hide & Unhide Sheets Based on the Response
- Recommended Articles
- How to Work with MsgBox Yes/No Response?
How to Work with MsgBox Yes/No Response?
You can download this VBA Message Box Yes or No Excel Template here – VBA Message Box Yes or No Excel Template
Example #1 – Copy and Paste based on Response
Look at the below code.
Code:
Sub MessageBox_Yes_NO_Example1() Dim AnswerYes As String Dim AnswerNo As String AnswerYes = MsgBox("Do you Wish to Copy?", vbQuestion + vbYesNo, "User Repsonse") If AnswerYes = vbYes Then Range("A1:A2").Copy Range("C1") Else Range("A1:A2").Copy Range("E1") End If End Sub
Explanation:
The above has declared the variable as String i.e.
Dim AnswerYes As String
In the next line, we have assigned the value through a message box asking, “Do you wish to copy?”.
AnswerYes = MsgBox("Do You Wish to Copy?", vbQuestion + vbYesNo, "User Repsonse")
Now, the IF statement evaluates the response given through the message box. For example, if the message box result is vbYes, it will copy the range A1 to A2 and paste it into cell C1.
If AnswerYes = vbYes Then Range("A1:A2").Copy Range("C1")
If the response given by the message box is No, then it will copy the range A1 to A2 and paste it into cell E1.
Else Range("A1:A2").Copy Range("E1") End If
We have entered a few values in cells A1 and A2 now.
Now, we will run the code using the F5 key, or through the run option, a message box will appear in front of us and ask for our response.
If we click “Yes,” it will copy the range A1 to A2 and paste it into the C1 cell. Now, we will click on “Yes” and see the result.
So, it has performed the task assigned if the response is YES.
Now again, we will run the code.
This time we will select No and see what happens.
Yes, it performed the task assigned in the code i.e.
Else
Range("A1:A2").Copy Range("E1")
Example #2 – Hide & Unhide Sheets Based on the Response
The below code will hide all the sheets except the active sheet if the response is yes.
Code:
Sub HideAll() Dim Answer As String Dim Ws As Worksheet Answer = MsgBox("Do you Wish to Hide All?", vbQuestion + vbYesNo, "Hide") If Answer = vbYes Then For Each Ws In ActiveWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden Next Ws ElseIf Answer = vbNo Then MsgBox "You have selected not to hide the sheets", vbInformation, "No Hide" End If End Sub
The above code will hide all the worksheets except the sheet we are in right now if the response from the message box is YES.
If the response from the message box is NO, it will display the message box saying, “You have selected not to hide the sheets.”
Similarly, the below code will unhide the sheet if the response is Yes.
Code:
Sub UnHideAll() Dim Answer As String Dim Ws As Worksheet Answer = MsgBox("Do you Wish to Unhide All?", vbQuestion + vbYesNo, "Hide") If Answer = vbYes Then For Each Ws In ActiveWorkbook.Worksheets Ws.Visible = xlSheetVeryHidden Next Ws ElseIf Answer = vbNo Then MsgBox "You have selected not to Unhide the sheets", vbInformation, "No Hide" End If End Sub
It works the same as the hide sheet code. If yes, it will unhide. If not, it will not unhide.
Recommended Articles
This article has been a guide to VBA Message Box. Here, we discuss creating a Yes or No response in the Excel VBA using MsgBox, practical examples, and a downloadable Excel template. Below you can find some useful Excel VBA articles: –
- VBA Find Next
- VBA ISERROR
- VBA Collection Object
- VBA Text Function
- VBA Save As