Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Keycode constants |
vblr6.chm1106124 |
vblr6.chm1106124 |
office |
9014afdc-a5ab-8f25-529f-45c9adf27eef |
12/11/2018 |
medium |
The following constants can be used anywhere in your code in place of the actual values.
Constant | Value | Description |
---|---|---|
vbKeyLButton | 0x1 | Left mouse button |
vbKeyRButton | 0x2 | Right mouse button |
vbKeyCancel | 0x3 | CANCEL key |
vbKeyMButton | 0x4 | Middle mouse button |
vbKeyBack | 0x8 | BACKSPACE key |
vbKeyTab | 0x9 | TAB key |
vbKeyClear | 0xC | CLEAR key |
vbKeyReturn | 0xD | ENTER key |
vbKeyShift | 0x10 | SHIFT key |
vbKeyControl | 0x11 | CTRL key |
vbKeyMenu | 0x12 | MENU key |
vbKeyPause | 0x13 | PAUSE key |
vbKeyCapital | 0x14 | CAPS LOCK key |
vbKeyEscape | 0x1B | ESC key |
vbKeySpace | 0x20 | SPACEBAR key |
vbKeyPageUp | 0x21 | PAGE UP key |
vbKeyPageDown | 0x22 | PAGE DOWN key |
vbKeyEnd | 0x23 | END key |
vbKeyHome | 0x24 | HOME key |
vbKeyLeft | 0x25 | LEFT ARROW key |
vbKeyUp | 0x26 | UP ARROW key |
vbKeyRight | 0x27 | RIGHT ARROW key |
vbKeyDown | 0x28 | DOWN ARROW key |
vbKeySelect | 0x29 | SELECT key |
vbKeyPrint | 0x2A | PRINT SCREEN key |
vbKeyExecute | 0x2B | EXECUTE key |
vbKeySnapshot | 0x2C | SNAPSHOT key |
vbKeyInsert | 0x2D | INSERT key |
vbKeyDelete | 0x2E | DELETE key |
vbKeyHelp | 0x2F | HELP key |
vbKeyNumlock | 0x90 | NUM LOCK key |
A key — Z key
The A key through the Z key are the same as the ASCII equivalents A–Z.
Constant | Value | Description |
---|---|---|
vbKeyA | 65 | A key |
vbKeyB | 66 | B key |
vbKeyC | 67 | C key |
vbKeyD | 68 | D key |
vbKeyE | 69 | E key |
vbKeyF | 70 | F key |
vbKeyG | 71 | G key |
vbKeyH | 72 | H key |
vbKeyI | 73 | I key |
vbKeyJ | 74 | J key |
vbKeyK | 75 | K key |
vbKeyL | 76 | L key |
vbKeyM | 77 | M key |
vbKeyN | 78 | N key |
vbKeyO | 79 | O key |
vbKeyP | 80 | P key |
vbKeyQ | 81 | Q key |
vbKeyR | 82 | R key |
vbKeyS | 83 | S key |
vbKeyT | 84 | T key |
vbKeyU | 85 | U key |
vbKeyV | 86 | V key |
vbKeyW | 87 | W key |
vbKeyX | 88 | X key |
vbKeyY | 89 | Y key |
vbKeyZ | 90 | Z key |
0 key — 9 key
The 0 key through 9 key are the same as their ASCII equivalents 0–9.
Constant | Value | Description |
---|---|---|
vbKey0 | 48 | 0 key |
vbKey1 | 49 | 1 key |
vbKey2 | 50 | 2 key |
vbKey3 | 51 | 3 key |
vbKey4 | 52 | 4 key |
vbKey5 | 53 | 5 key |
vbKey6 | 54 | 6 key |
vbKey7 | 55 | 7 key |
vbKey8 | 56 | 8 key |
vbKey9 | 57 | 9 key |
Numeric keypad keys
The following constants represent keys on the numeric keypad.
Constant | Value | Description |
---|---|---|
vbKeyNumpad0 | 0x60 | 0 key |
vbKeyNumpad1 | 0x61 | 1 key |
vbKeyNumpad2 | 0x62 | 2 key |
vbKeyNumpad3 | 0x63 | 3 key |
vbKeyNumpad4 | 0x64 | 4 key |
vbKeyNumpad5 | 0x65 | 5 key |
vbKeyNumpad6 | 0x66 | 6 key |
vbKeyNumpad7 | 0x67 | 7 key |
vbKeyNumpad8 | 0x68 | 8 key |
vbKeyNumpad9 | 0x69 | 9 key |
vbKeyMultiply | 0x6A | MULTIPLICATION SIGN (*) key |
vbKeyAdd | 0x6B | PLUS SIGN (+) key |
vbKeySeparator | 0x6C | ENTER key |
vbKeySubtract | 0x6D | MINUS SIGN (—) key |
vbKeyDecimal | 0x6E | DECIMAL POINT (.) key |
vbKeyDivide | 0x6F | DIVISION SIGN (/) key |
Function keys
The following constants represent function keys.
Constant | Value | Description |
---|---|---|
vbKeyF1 | 0x70 | F1 key |
vbKeyF2 | 0x71 | F2 key |
vbKeyF3 | 0x72 | F3 key |
vbKeyF4 | 0x73 | F4 key |
vbKeyF5 | 0x74 | F5 key |
vbKeyF6 | 0x75 | F6 key |
vbKeyF7 | 0x76 | F7 key |
vbKeyF8 | 0x77 | F8 key |
vbKeyF9 | 0x78 | F9 key |
vbKeyF10 | 0x79 | F10 key |
vbKeyF11 | 0x7A | F11 key |
vbKeyF12 | 0x7B | F12 key |
vbKeyF13 | 0x7C | F13 key |
vbKeyF14 | 0x7D | F14 key |
vbKeyF15 | 0x7E | F15 key |
vbKeyF16 | 0x7F | F16 key |
See also
- Constants (Visual Basic for Applications)
[!includeSupport and feedback]
- Статьи
KeyCode | Hex | Button name |
---|---|---|
8 | 0x08 | BackSpace |
9 | 0x09 | Tab |
13 | 0x0D | Enter |
20 | 0x14 | CapsLock |
27 | 0x1B | Esc |
32 | 0x20 | пробел |
33 | 0x21 | PageUp |
34 | 0x22 | PageDown |
35 | 0x23 | End |
36 | 0x24 | Home |
37 | 0x25 | Стрелка влево |
38 | 0x26 | Стрелка вверх |
39 | 0x27 | Стрелка вправо |
40 | 0x28 | Стрелка вниз |
44 | 0x2C | PrintScreen |
45 | 0x2D | Insert |
46 | 0x2E | Delete |
48 | 0x30 | 0 |
49 | 0x31 | 1 |
50 | 0x32 | 2 |
51 | 0x33 | 3 |
52 | 0x34 | 4 |
53 | 0x35 | 5 |
54 | 0x36 | 6 |
55 | 0x37 | 7 |
56 | 0x38 | 8 |
57 | 0x39 | 9 |
65 | 0x41 | A |
66 | 0x42 | B |
67 | 0x43 | C |
68 | 0x44 | D |
69 | 0x45 | E |
70 | 0x46 | F |
71 | 0x47 | G |
72 | 0x48 | H |
73 | 0x49 | I |
74 | 0x4A | J |
75 | 0x4B | K |
76 | 0x4C | L |
77 | 0x4D | M |
78 | 0x4E | N |
79 | 0x4F | O |
80 | 0x50 | P |
81 | 0x51 | Q |
82 | 0x52 | R |
83 | 0x53 | S |
84 | 0x54 | T |
85 | 0x55 | U |
86 | 0x56 | V |
87 | 0x57 | W |
88 | 0x58 | X |
89 | 0x59 | Y |
90 | 0x5A | Z |
91 | 0x5B | Win(Л) |
92 | 0x5C | Win(Пр) |
96 | 0x60 | Доп(0) |
97 | 0x61 | Доп(1) |
98 | 0x62 | Доп(2) |
99 | 0x63 | Доп(3) |
100 | 0x64 | Доп(4) |
101 | 0x65 | Доп(5) |
102 | 0x66 | Доп(6) |
103 | 0x67 | Доп(7) |
104 | 0x68 | Доп(8) |
105 | 0x69 | Доп(9) |
106 | 0x6A | Доп(*) |
107 | 0x6B | Доп(+) |
109 | 0x6D | Доп(-) |
110 | 0x6E | Доп(,) |
111 | 0x6F | Доп(/) |
112 | 0x70 | F1 |
113 | 0x71 | F2 |
114 | 0x72 | F3 |
115 | 0x73 | F4 |
116 | 0x74 | F5 |
117 | 0x75 | F6 |
118 | 0x76 | F7 |
119 | 0x77 | F8 |
120 | 0x78 | F9 |
121 | 0x79 | F10 |
122 | 0x7A | F11 |
123 | 0x7B | F12 |
124 | 0x7C | F13 |
125 | 0x7D | F14 |
126 | 0x7E | F15 |
127 | 0x7F | F16 |
128 | 0x80 | F17 |
129 | 0x81 | F18 |
130 | 0x82 | F19 |
131 | 0x83 | F20 |
132 | 0x84 | F21 |
133 | 0x85 | F22 |
134 | 0x86 | F23 |
135 | 0x87 | F24 |
144 | 0x90 | Numlock |
166 | 0xA6 | Browser Back |
167 | 0xA7 | Browser Forward |
168 | 0xA8 | Browser Refresh |
169 | 0xA9 | Browser Stop |
170 | 0xAA | Browser Search |
171 | 0xAB | Browser Favorites |
172 | 0xAC | Browser Home |
173 | 0xAD | Volume Mute |
174 | 0xAE | Volume Down |
175 | 0xAF | Volume Up |
176 | 0xB0 | Next Track |
177 | 0xB1 | Previous Track |
178 | 0xB2 | Stop Media |
179 | 0xB3 | Play/Pause |
180 | 0xB4 | Start Mail |
181 | 0xB5 | Select Media |
182 | 0xB6 | Start App 1 |
183 | 0xB7 | Start App 2 |
- 50530 просмотров
ПОПУЛЯРНЫЕ ПРОГРАММЫ
Имитация нажатия клавиш на клавиатуре в VBA Excel с помощью оператора SendKeys, в том числе эмуляция нажатия сочетаний клавиш. Синтаксис, коды, примеры.
Параметры оператора SendKeys:
Параметр | Описание |
---|---|
string | Обязательный параметр. Строковое выражение, возвращающее код клавиши (сочетания клавиш). |
wait | Необязательный параметр. Логическое значение, определяющее режим ожидания. False (по умолчанию) – контроль процедуре возвращается сразу после отправки кода клавиш. True – перед возвратом контроля процедуре коды клавиш обрабатываются. |
Имитация нажатия клавиш
Эмуляция нажатия алфавитно-цифровых клавиш из кода VBA Excel, не представляющих спецсимволы: параметру string
задается значение символа в прямых кавычках, например, "А"
, "Абвгд"
, "356"
.
Имитация нажатия клавиш, представляющих спецсимволы: параметру string
задается значение символа в фигурных скобках, например, "{^}"
, "{)}"
.
Спецсимволы, которые следует заключать в фигурные скобки: плюс +
, возведение в степень ^
, знак процента %
, тильда ~
, круглые скобки ()
, квадратные скобки []
и сами фигурные скобки {}
. Символы фигурных скобок указываются так: "{{}"
и "{}}"
.
Для эмуляции нажатия специальных клавиш, включая функциональные и клавиши управления курсором, используются специальные коды, заключенные в фигурные скобки.
Фигурные скобки используются и для имитации нескольких нажатий одной клавиши из кода VBA Excel. В этом случае параметр string
записывается в виде {клавиша число}
, где число – количество нажатий. Например: "{а 10}"
.
Коды специальных клавиш
Клавиша | Код |
---|---|
BACKSPACE | {BACKSPACE} или {BS} |
BREAK | {BREAK} |
CAPS LOCK | {CAPSLOCK} |
DEL или DELETE | {DELETE} или {DEL} |
СТРЕЛКА ВНИЗ | {DOWN} |
END | {END} |
ENTER | {ENTER} или ~ |
ESC | {ESC} |
HELP | {HELP} |
HOME | {HOME} |
INS или INSERT | {INSERT} или {INS} |
СТРЕЛКА ВЛЕВО | {LEFT} |
NUM LOCK | {NUMLOCK} |
PAGE DOWN | {PGDN} |
PAGE UP | {PGUP} |
PRINT SCREEN | {PRTSC} |
СТРЕЛКА ВПРАВО | {RIGHT} |
SCROLL LOCK | {SCROLLLOCK} |
TAB | {TAB} |
СТРЕЛКА ВВЕРХ | {UP} |
F1 … F16 | {F1} … {F16} |
Эмуляция сочетаний клавиш
Чтобы указать сочетание клавиш с SHIFT, CTRL, ALT или их комбинацией, необходимо добавить перед кодом клавиши один или несколько следующих кодов:
Клавиша | Код |
---|---|
SHIFT | + |
CTRL | ^ |
ALT | % |
Чтобы указать, что клавиши SHIFT, CTRL и ALT в любом сочетании необходимо удерживать, нажимая несколько других клавиш, заключите код для последних клавиш в круглые скобки. Например, чтобы указать, что нужно удерживать клавишу SHIFT, нажимая клавиши а, б, в, г, д, введите "+(абвгд)"
.
Важное примечание:
Применение оператора SendKeys может приводить к автоматическому отключению* правого цифрового блока клавиатуры (переключает на стрелки и специальные клавиши). Чтобы вернуть исходную функциональность цифрового блока, необходимо в конце процедуры применить имитацию нажатия клавиши «NUM LOCK»: SendKeys "{NUMLOCK}"
. К сожалению, работает не всегда.
* Обнаружено в Windows 8.1 (Excel 2016).
Примеры с оператором SendKeys
Коды примеров запускаются через кнопку на рабочем листе, иначе имитация нажатия клавиш произойдет в окне редактора VBA с записью символов внутри процедуры. Попробуйте, ради интереса, запустить код первого примера из редактора VBA.
Пример 1
Заполняем первые три ячейки столбца «A» различными значениями, имитируя нажатия клавиш из кода VBA Excel:
Sub Primer1() ‘Выбираем первую ячейку Range(«A1»).Select ‘Нажимаем клавиши «а», «б» и «в» SendKeys «абв» ‘Нажимаем «ENTER» SendKeys «~» ‘Нажимаем клавиши «1», «2», «3» и «ENTER» SendKeys «123 ~» ‘Нажимаем клавишу «7» пять раз и «ENTER» SendKeys «{7 5} ~» ‘Активируем правый цифровой блок ‘SendKeys «{NUMLOCK}» End Sub |
Пример 2
Раскрываем с помощью кода VBA Excel автофильтр или выпадающий список (имитация нажатия сочетания клавиш ALT+↓
):
Sub Primer2() ‘Выбираем ячейку с автофильтром или раскрывающимся списком Range(«D1»).Select ‘Раскрываем список SendKeys «%{DOWN}» ‘Активируем правый цифровой блок ‘SendKeys «{NUMLOCK}» End Sub |
Пример 3
Еще три варианта эмуляции нажатия сочетаний клавиш:
‘Создание новой книги SendKeys «^n» ‘Открытие Диспетчера имен SendKeys «^{F3}» ‘Открытие Диспетчера задач SendKeys «^+{ESC}» |
As a VBA developer you sometimes need to use a key or a combination of keys to run a procedure without using the command button on a UserForm. This is possible with the VBA onkey method.
Syntax
The syntax for the OnKey
method is:
Application.OnKey (key, procedure)
Parameters/Arguments
The syntax has two
parameters/arguments which are key
and procedure
Key
The Key argument can specify
any single key combined with ALT, CTRL, or SHIFT, or any combination of these
keys. Each key is represented by one or more characters.
Normal alphanumeric keys are
denoted by themselves (e.g. “a”, “A”, “1”).
Example:
Assign “ActivateSheet” to key A.
Syntax: Application.Onkey “A”, “ActivateSheet”
It is also possible to use special
characters such as + ^ % { ) ~ ) and special keys like BACKSPACE, END etc. To
do that, you have to use curly braces {}.
Example: Assign “SelectRange” to a) BACKSPACE key b) %
key.
- Syntax:
Application.Onkey “{BACKSPACE}”, “SelectRange”
- Syntax:
Application.Onkey “{%}”, “SelectRange”
Below is the list of keys than
can be used and their corresponding codes
Key | Code |
BACKSPACE | {BACKSPACE} or {BS} |
BREACK | {BREAK} |
CAPS LOCK | {CAPSLOCK} |
CLEAR | {CLEAR} |
DELETE or DEL | {DELETE} or {DEL} |
DOWN ARROW | {DOWN} |
END | {END} |
ENTER (Numeric keypad) | {ENTER} |
ENTER | ~ (tilde) |
ESC | {ESCAPE} or {ESC} |
HELP | {HELP} |
HOME | {HOME} |
INS | {INSERT} |
LEFT ARROW | {LEFT} |
NUM LOCK | {NUMLOCK} |
PAGE DOWN | {PGDN} |
PAGE UP | {PGUP} |
RETURN | {RETURN} |
RIGHT ARROW | {RIGHT} |
SCROLL LOCK | {SCROLLDOWN} |
TAB | {TAB} |
UP ARROW | {UP} |
F1 Through F15 | {F1} Through {F15} |
You can also use keys
combined with Shift and/or Ctrl and/or Alt and/or Command. To do so, use the
following table.
To combine keys with | Begin the key code with |
Shift | + (plus sign) |
Ctrl | ^ (caret) |
Alt | % (percent sign) |
Example: Assign “CopySheet” to the key sequence Shift+Ctrl+Right arrow.
Syntax: Application.Onkey “+^{RIGHT}”, “CopySheet”
Procedure
It is an optional (can be
omitted) string indicating the name of the procedure to be run. When the
procedure is omitted, nothing happens when key is pressed, key reverts to its
normal function in Microsoft Excel. In other words, if we write the following code:
Application.Onkey “{ENTER}”,
the procedure argument has been omitted. In this case when the ENTER key will be pressed; it will simply execute the function that was initially assigned to it by MS Excel. This syntax is used to enable any key that was disabled.
When the
procedure argument of the OnKey Syntax is an empty string, it is to disable the
said key.
For
example, if we want to disable the ENTER key, we shall use the following code:
Application.Onkey “{ENTER}”, “”.
Application
In the following lines we
are going to apply the usage of OnKey method with a step by step tutorial for
beginners through 2 examples. It is advisable for you follow the steps and do
it yourself.
While assuming that you know
how to use the VBA/Excel Editor (If not, refer to the following article: How to create a procedure in Excel/VBA from
the same author), let’s create 2 procedures and assign key/keys to each of them
Activity Number 1
For a start we shall create
a procedure called “Testing” in the Module1 of the VBA Editor and write the
following code:
The ENTER key will be assigned
to the procedure in Sheet1, meaning that whenever the ENTER key will be pressed
the following message will pop up “Hello
World, My Onkey Method is Working!!!”
As we saw in the table above
the corresponding code for the ENTER key is “~”. So the syntax to assign the
ENTER key to the “Testing” procedure is:
Application.OnKey "~", "Testing"
It
should be noted that this piece of code can be written directly in the
worksheet where we want it to be executed or in a module as a procedure and
called from the said worksheet.
If we
opt for the first option then, identify the sheet and double click on it and
write the following code
Private Sub Worksheet_Activate() Application.OnKey "~", "Testing" End Sub
Try it and make sure you get the following message box when you press the ENTER key in Sheet1.
If that is the case then
congratulations! You have written your first OnKey method successfully. The
next examples will follow the same pattern with less explanation this time.
Activity Number 2
In this second activity, we
are going to disable the arrow keys that is {UP}, {DOWN}, {LEFT} and {RIGHT}.
Create a procedure named “DisableArrowkeys” in Module1 and write the following code
Sub DisableArrowKeys() Application.OnKey "{UP}", "" Application.OnKey "{DOWN}", "" Application.OnKey "{LEFT}", "" Application.OnKey "{RIGHT}", "" End Sub
Note the use of ""
in the place of the procedure argument. This is to indicate that the key has been disabled as it was said earlier. If you wish to enable the key again simply remove it.
See also: Simulating a key press with Application.SendKeys
Message Box is one of the most frequently used functions in VBA Macro. The message box is a dialogue box that appears on the screen as an extra window. The dialogue box that appeared asks input from the user and returns a constant/code/number accordingly or it can use to display messages. In this article, we will learn how to create different types of message boxes in VBA Macro.
Message Box
A message box is a dialogue box that displays information that can be text, date, number, etc. like as shown in the below image. In Excel, we can easily create a message box using VBA.
Parts of a message box:
1. Title: The title of a message box specifies what properties or functions will this dialogue box performs. While writing a message box in VBA macro it is not mandatory to write a title. A title does not have multiple lines. If a title is not mentioned then by default the title becomes Microsoft Excel.
2. Prompt: The prompt is the heart of the message box. It specifies the work to be done or the information provided in a detailed manner. While writing a message box function it is mandatory to write a prompt statement. You can also display tables, dates, and numbers in the prompt. You can also add multiple lines in the prompt area.
3. Buttons: While working with basic Excel, you might have configured the different buttons that appear in a dialogue box. For example, Yes/No, Retry, Help, Abort/Retry/Ignore, etc. You can create and use any of the buttons, according to your requirement. While writing a message box function it is not mandatory to specify the buttons. By default, Ok appears.
Creating a Basic Message Box in VBA
In Excel, we can easily create a message box with the help of the MsgBox function.
Syntax:
Msgbox “prompt(mandatory)”, buttons(temporary), “title(temporary)”, “helpfile(temporary)”, “context(temporary)”
Here,
- Prompt: Prompt is the detailed information of the MsgBox. It is mandatory to add a prompt while writing the MsgBox function. You can also add multiple lines to the prompt.
- Buttons: It is the temporary argument that you wish to add. By default, it shows only the Ok button. To add custom buttons, you have the code for each button. For example, vbRetryCancel, vbOkOnly.
- Title: It is the temporary argument of the MsgBox function. You cannot add multiple titles to a message box.
- HelpFile: This is a very rare argument that is passed on while creating a MsgBox. This argument is only provided when you are using a help button. When you are passing the help file, you have to use context arguments also.
- Context: It is only used with the help file and help button. You need to have a numeric help context number to the appropriate help topic.
Follow the below steps:
Step 1: The MsgBox keyword is used to create a message box is MsgBox. So write MsgBox. Start with a double quote and write the prompt you want to display. Press Enter.
Step 2: Click on the Run button.
Step 3: The Message Box appears. Here, the VBA code has stopped running and will not get executed until we select any of the buttons in the message box. Click Ok.
Step 4: The VBA code resumes.
Buttons in MessageBox
When you have typed a prompt in the MsgBox function. The next argument is separated with a comma(,). Now, the VBA editor gives us a list of buttons that can be added to the MsgBox function. You can select and add the button according to your requirements.
The types of buttons in the MsgBox.
1. vbOkOnly(Default): This is the default button that appears. To create this button follow the following steps:
Step 1: Write the code. vbOkOnly is the code that helps create only the Ok button.
Step 2: The MsgBox contains only the Ok button.
2. vbOkCancel: vbOkCancel code tells the VBA compiler to show Ok and cancel buttons while displaying the MsgBox. To create this button follow the following steps:
Step 1: Write the code. vbOkCancel is the code that helps create the Ok and Cancel buttons.
Step 2: The MsgBox contains both Ok and Cancel.
3. vbAbortRetryIgnore: This code displays Abort, Retry and Ignore buttons in the message box. To create this button follow the following steps:
Step 1: Write the code. vbAbortRetryIgnore is the code that helps create the Abort, Retry, and Ignore buttons.
Step 2: The MsgBox contains all three Abort, Retry and Ignore.
4. vbYesNoCancel: vbYesNoCancel code displays Yes, No, and Cancel buttons in the message box. To create this button follow the following steps:
Step 1: Write the code. vbYesNoCancel is the code that helps create the Yes, No, and Cancel.
Step 2: The MsgBox contains all three Yes, No, and Cancel.
5. vbYesNo: vbYesNo code displays Yes and No buttons in the message box. To create this button follow the following steps:
Step 1: Write the code. vbYesNo is the code that helps create the Yes and No.
Step 2: The MsgBox contains both Yes and No.
6. vbRetryCancel: vbRetryCancel code displays Retry and Cancel buttons in the message box. To create this button follow the following steps:
Step 1: Write the code. vbRetryCancel is the code that helps create the Retry and Cancel.
Step 2: The MsgBox contains both Retry and Cancel.
7. vbDefaultButton2: You can use any of the default buttons. There are four types of default buttons. vbDefaultButton1, vbDefaultButton2, vbDefaultButton3, vbDefaultButton4. Here, vbDefaultButton2 is the button that is selected by default when a Msgbox appears. If you press Enter, then it automatically gets selected. To create this button follow the following steps:
Step 1: Write the code. Using vbAbortRetryIgnore creates three-button Abort, Retry and Ignore. vbDefaultButton2 is the code that helps us select the second default button i.e. Retry.
Step 2: The MsgBox appears and the default is Retry.
Different Icons in Excel VBA
While working with basic excel. You have come across different warnings and information. These all are represented with symbols. For example, a yellow exclamation for warning, a blue color question marks for information, etc. Here, we have discussed some of the icons that can appear in a message box.
1. vbCritical: This icon is a red cross. This red cross is used to display a critical message. To create this icon follow the following steps:
Step 1: Write the code. vbCritical creates a red cross.
Step 2: The message box with a critical icon appears.
2. vbQuestion: This icon is a blue question mark. This blue question mark is used to display when you forgot something to choose in a procedure. To create this icon follow the following steps:
Step 1: Write the code. vbQuestion creates a blue Question Mark.
Step 2: The message box with a Question icon appears.
3. vbExclamation: This icon is a yellow exclamation mark. It is used to represent an error when the entered data doesn’t match with the already present data. To create this icon follow the following steps:
Step 1: Write the code. vbExclamation creates a yellow exclamation mark.
Step 2: The message box with a ! (exclamation) icon appears.
4. vbInformation: This icon is a blue I mark that represents information. To create this icon follow the following steps:
Step 1: Write the code. vbInformation creates a blue I information mark.
Step 2: The message box with an i(information) icon appears.
Values returned by Buttons
Till now, you have studied how to create a message box and the different buttons associated with it. Now, we will learn how you can create nested message boxes and also with some conditions that are more practical in the real designing of a dialogue box. A message box returns a code or a constant according to the buttons applied. Some of the most commonly used constants and their return value are given in the table below.
Constant | Value |
---|---|
vbOKOnly | 0 |
vbOKCancel | 1 |
vbAbortRetryIgnore | 2 |
vbYesNoCancel | 3 |
vbYesNo | 4 |
vbRetryCancel | 5 |
Note: You can use values as well as constant interchangeably while comparing the boolean expressions.
For example, given Yes, No, and Cancel buttons. Display a message box accordingly. So to do this task follow the following steps:
Step 1: Write the code. The initial MsgBox will return a value and it will get stored in a variable name ans. If you click yes, then it will go inside the if condition else it will output the other one. Click on the Run button.
Step 2: A dialogue box appears. Click on Yes.
Step 3: A dialogue box appears. Click Ok.
Editing Title in a Msg Box
You can edit the title in a message box. By default, it shows Microsoft Excel as the title. In the MsgBox, function the third argument is for writing your custom title. It is a temporary argument. Follow are the following steps:
Step 1: Write the code. The third argument is your custom title.
Step 2: A dialogue box with the title “Be a geek” appears.