Applies To
Application Object.
Description
Runs a specified procedure when a particular key or key combination is pressed.
Syntax
object.OnKey(key, procedure)
object
Required. The Application object.
key
Required. A string indicating the keystroke.
procedure
Optional. A string indicating the name of the procedure. If procedure is "" (empty text), nothing happens when key is pressed. This form of OnKey disables the normal meaning of keystrokes in Microsoft Excel. If procedure is omitted, key reverts to its normal meaning in Microsoft Excel, and any special key assignments made with previous OnKey methods are cleared.
Remarks
The key argument can specify any single key; any key combined with ALT, CTRL, or SHIFT, or any combination of those keys (in Windows); or COMMAND, CTRL, OPTION, or SHIFT, or any combination of those keys (on the Macintosh). Each key is represented by one or more characters, such as "a" for the character a, or "{ENTER}" for the ENTER key.
To specify characters that aren't displayed when you press the key, such as ENTER or TAB, use the codes shown in the following table. Each code in the table represents one key on the keyboard.
Key |
Code |
BACKSPACE |
"{BACKSPACE}" or "{BS}" |
BREAK |
"{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 |
"{SCROLLLOCK}" |
TAB |
"{TAB}" |
UP arrow |
"{UP}" |
F1 through F15 |
"{F1}" through "{F15}" |
In Windows, you can also specify keys combined with SHIFT and/or CTRL and/or ALT. On the Macintosh, you can also specify keys combined with SHIFT and/or CTRL and/or OPTION and/or COMMAND. To specify a key combined with another key or keys, use the following table.
To combine with |
Precede the key code by |
SHIFT |
"+" (plus sign) |
CTRL |
"^" (caret) |
ALT or OPTION |
"%" (percent sign) |
COMMAND |
"*" (asterisk) |
To assign a procedure to one of the special characters (+, ^, %, and so on), enclose the character in braces. See the example for details.
Example
This example assigns my_InsertItem_Procedure to the key sequence CTRL+PLUS SIGN and assigns my_SpecialPrint_Procedure to the key sequence SHIFT+CTRL+RIGHT ARROW.
Application.OnKey "^{+}", "my_InsertItem_Procedure" Application.OnKey "+^{RIGHT}", "my_SpecialPrint_Procedure"
This example returns SHIFT+CTRL+RIGHT ARROW to its normal meaning.
Application.OnKey "+^{RIGHT}"
This example disables the SHIFT+CTRL+RIGHT ARROW key sequence.
Application.OnKey "+^{RIGHT}", ""