You’re just using the MsgBox
method as a Sub
. In VB6/VBA a Sub
call either doesn’t use brackets, or uses the Call
keyword.
MsgBox "hello world", vbOKCancel
or
Call MsgBox("hello world", vbOKCancel)
The brackets come into play when using the method as a function (ie you want the return value)
Dim msgResult
msgResult = MsgBox("hello world", vbOKCancel)
I would guess that, since you’re using vbOKCancel
, this is the version you’ll end up using to find out what the user clicked.
Использование функции MsgBox в VBA Excel, ее синтаксис и параметры. Значения, возвращаемые функцией MsgBox. Примеры использования.
Функция MsgBox предназначена в VBA Excel для вывода сообщения в диалоговом окне, ожидания нажатия кнопки и возврата значения типа Integer, указывающего на то, какая кнопка была нажата. Для упрощения восприятия информации, в этой статье не рассматриваются параметры, связанные с контекстной справкой и модальностью диалогового окна MsgBox.
Синтаксис функции
MsgBox ( Prompt [, Buttons ] [, Title ])
Обязательным параметром функции MsgBox является Prompt, если Buttons и Title явно не указаны, используются их значения по умолчанию. Кроме того, если необязательные параметры не указаны и возвращаемое значение не присваивается переменной, сообщение не заключается в скобки:
Пример 1
Sub Test1() MsgBox «Очень важное сообщение!» End Sub |
Параметры функции
Параметр | Описание | Значение по умолчанию |
---|---|---|
Prompt* | Обязательный параметр. Выражение типа String, отображаемое в диалоговом окне в виде сообщения. Разделить на строки можно с помощью константы vbNewLine. | Нет |
Buttons | Необязательный параметр. Числовое выражение, которое представляет собой сумму значений, задающих номер и тип отображаемых кнопок, стиль используемого значка, тип кнопки по умолчанию. | 0 |
Title | Необязательный параметр. Выражение типа String, отображаемое в заголовке диалогового окна. | Имя приложения** |
*Максимальная длина параметра Prompt составляет примерно 1024 знака и зависит от их ширины.
**В Excel по умолчанию в заголовке MsgBox выводится надпись «Microsoft Excel».
Константы параметра «Buttons»
Тип и количество кнопок
Константа | Описание | Значение |
---|---|---|
vbOKOnly | Отображается только кнопка OK. | 0 |
vbOKCancel | Отображаются кнопки OK и Cancel (Отмена). | 1 |
vbAbortRetryIgnore | Отображаются кнопки Abort (Прервать), Retry (Повторить) и Ignore (Пропустить). | 2 |
vbYesNoCancel | Отображаются кнопки Yes (Да), No (Нет) и Cancel (Отмена). | 3 |
vbYesNo | Отображаются кнопки Yes (Да) и No (Нет). | 4 |
vbRetryCancel | Отображаются кнопки Retry (Повторить) и Cancel (Отмена). | 5 |
Стиль значка
Константа | Описание | Значение |
---|---|---|
vbCritical | Отображается значок Critical — Критичное сообщение, сообщение об ошибке. | 16 |
vbQuestion | Отображается значок Question — Сообщение с вопросом. | 32 |
vbExclamation | Отображается значок Exclamation — Предупреждающее сообщение. | 48 |
vbInformation | Отображается значок Information — Информационное сообщение. | 64 |
Для просмотра отображаемых значков, скопируйте код в свой модуль и запустите на выполнение:
Пример 2
Sub Test2() Dim a As Integer a = MsgBox(«Критичное сообщение, сообщение об ошибке», 16) a = MsgBox(«Сообщение с вопросом», 32) a = MsgBox(«Предупреждающее сообщение», 48) a = MsgBox(«Информационное сообщение», 64) End Sub |
Кнопка по умолчанию
Константа | Описание | Значение |
---|---|---|
vbDefaultButton1 | По умолчанию активна первая кнопка. | 0 |
vbDefaultButton2 | По умолчанию активна вторая кнопка. | 256 |
vbDefaultButton3 | По умолчанию активна третья кнопка. | 512 |
Возвращаемые значения
Константа | Кнопка | Значение |
---|---|---|
vbOK | OK | 1 |
vbCancel | Отмена | 2 |
vbAbort | Прервать | 3 |
vbRetry | Повторить | 4 |
vbIgnore | Пропустить | 5 |
vbYes | Да | 6 |
vbNo | Нет | 7 |
Значение, возвращаемое функцией MsgBox, используется для выбора дальнейших действий исполняемой программы в зависимости от нажатой кнопки.
Для третьего примера зададим следующие параметры первой функции MsgBox:
- Prompt = «Выберите кнопку!»
- Buttons = 323 (3 (vbYesNoCancel) + 64 (vbInformation) + 256 (vbDefaultButton2))
- Title = «Выбор кнопки»
Вторая функция MsgBox используется как простое информационное сообщение с параметрами по умолчанию.
Пример 3
Sub Test3() Dim a As Integer a = MsgBox(«Выберите кнопку!», 323, «Выбор кнопки») If a = 6 Then MsgBox «Вы нажали кнопку: Да» ElseIf a = 7 Then MsgBox «Вы нажали кнопку: Нет» Else MsgBox «Вы нажали кнопку: Отмена» End If End Sub |
В этом примере, в зависимости от нажатой кнопки в первом диалоговом окне, во втором сообщении выводится название нажатой кнопки. Обратите внимание, что вторая кнопка в открывшемся первом окне MsgBox выделена по умолчанию и срабатывает при нажатии клавиши «Enter».
А что будет, если первое диалоговое окно из третьего примера закрыть крестиком? Проверьте сами.
Asked
7 years, 11 months ago
Viewed
879 times
When I try to compile I’m given this error:
Compile error:
Syntax error
Here is the code:
Public Sub ErrorHandler()
' The code is cleaned up by using ErrorHandler as a function because it has to be written out fewer times, and makes changing ErrorHandler easier
MsgBox("Error detected" & vbNewLine & vbNewLine & "Error " & Err.Number, vbCritical, "Error Handler: Error " & Err.Number)
End Sub
asked Jul 6, 2015 at 18:33
3
unless a subroutine is returning a value,i.e. being assigned to a variable there is no need to use paranthesis
MsgBox "Error detected" & vbNewLine & vbNewLine & "Error " & Err.Number, vbCritical, "Error Handler: Error " & Err.Number
if msgbox needs to give back an answer then, the following is the correct syntax
response = MsgBox ("Error detected" & vbNewLine & vbNewLine & "Error " & Err.Number & "Do you want to retry", vbYesNo, "Error Handler: Error " & Err.Number)
answered Jul 6, 2015 at 18:36
KrishnaKrishna
2,4511 gold badge26 silver badges31 bronze badges
4
new_men Пользователь Сообщений: 24 |
#1 23.10.2014 00:56:22 Добрый вечер! Ужасно запарила ошибка!!! Помогите начинающиму, пожалуйста.
При компаляции Expected variable or procedure,not module, вот что говорит. Подскажите пожалуйста с этой ситуацей, заступарился.
|
||
Doober Пользователь Сообщений: 2230 |
Забейте в поиск Msgbox по всему vba проекту и |
Юрий М Модератор Сообщений: 60762 Контакты см. в профиле |
#3 23.10.2014 01:39:02
Должно быть наоборот: пишем msgbox, а получаем MsgBox )) Согласен с Сергеем: где-то у Вас это слово используется. |
||
new_men Пользователь Сообщений: 24 |
Спасибо большое за направление Приду домой поищу. Пример взял из Вокенбаха. На работе попробовал сейчас , ошибку не выдает, сообщение выводит, только вот результат 5050 ))))) Это какое-то проклятие (или испытание) P/s На работе MsgBox не исправляет на Msgbox. |
Юрий М Модератор Сообщений: 60762 Контакты см. в профиле |
#5 23.10.2014 11:15:01
Это правильный результат. |
||
The_Prist Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
new_men Пользователь Сообщений: 24 |
#7 23.10.2014 12:17:34
Юрий, разобрался с результатом, спасибо)
|
||
JeyCi Пользователь Сообщений: 3387 |
#8 23.10.2014 12:53:46
навела красоту в вашем Msgbox
чтобы не гадать на кофейной гуще, кто вам отвечает и после этого не совершать кучу ошибок — обратитесь к собеседнику на ВЫ — ответ на ваш вопрос получите — а остальное вас не касается (п.п.п. на форумах) |
||||
- Remove From My Forums
-
Question
-
Howdy,
I understand that «MsgBox Error$» is an old syntax from Access2. In cleaning up code I’ve found 90 instances scattered around.
If I want to replace them with Err.Description at the least or even better something that will return the module and procedure. Along the lines of
MsgBox «Error » & Err.Number & » (» & Err.Description & «) in procedure » XXXXXXX & » of Module » YYYYYYYY
where XXXXX is the procedure name and YYYYY is the module.
Right now, I’ve been putting in the error handlers using MZ-Tools or manualy but if I want to do a find and replace for my Error$ I’m at a loss.
Ideas?
/Joe
Answers
-
If you merely want to replace
with
MsgBox Err.Description, vbCritical
or similar, you can do that in one fell swoop in the Edit | Replace dialog — set the Search scope to Current Project and click Replace All.
If you want to add the name of the procedure and module, you’d have to use the Microsoft Visual Basic for Applications Extensibility 5.3 library. Personally, I don’t think it’s worth the trouble — during development, I can keep track of where errors occur
myself, and I don’t think it’s useful for end users to see the procedure and module names.
Regards, Hans Vogelaar
-
Marked as answer by
Thursday, February 23, 2012 9:20 AM
-
Marked as answer by
-
Its a nice idea but you may need to think it through further. Error handling is a bit of an art and there are few hard and fast rules.
Your colleague probably left Error$ there for a reason (like he knew the module name by asking the user which form or report was in use when the error was encountered,so why would he want to spend hours putting in the procedure name????)
Probably the more important thing is what the code should do after the error message has been displayed — or whether the user should be given a more user friendly explanation.
For example:
- Once the error has occured, you could terminate the procedure by exitting out of it …. if the code has left database or recordset objects open, you may be better off to close them. Otherwise the user may find he cannot close the application, it
runs out of memory etc, etc - You could RESUME NEXT meaning the code goes back to the point where the erro occurred. Now this could generate even more error messages because of the initial error and look pretty bad …. but it would serve to ensure any instantiated objects are
likely to be closed - RESUME at some specific label in the code ….
- Or may be replce some error messages like:
- If err.number = 3000 then
- Msgbox «You must enter a valid value !!!», vbOKonly
- endif
- Resume Next
It is probable the application may need some cleaning up to handle errors in a more user friendly manner — and it may be you need to do more than simply add a procedure name. You could create a procedure to record errors and login data to a table then
decide which messages to analyse further with a view to cleaning up the application.
PG A bit of experimentation by trial and error often helps.
-
Marked as answer by
Bruce Song
Thursday, February 23, 2012 9:20 AM
- Once the error has occured, you could terminate the procedure by exitting out of it …. if the code has left database or recordset objects open, you may be better off to close them. Otherwise the user may find he cannot close the application, it
-
Further to what Hans V has recommended (which I agree with), I would suggest taking a closer look at «Debug.Print«, «Debug.Assert» and the Immediate (debugging) window in the VBA Code Editor, which you can show by holding
CTRL+G.
Matthew Slyman M.A. (Camb.)
-
Marked as answer by
Bruce Song
Thursday, February 23, 2012 9:20 AM
-
Marked as answer by