Runs a specified procedure when a particular key or key combination is pressed.
Syntax
expression.OnKey (Key, Procedure)
expression A variable that represents an Application object.
Parameters
| Name | Required/Optional | Data type | Description |
|---|---|---|---|
| Key | Required | String | A string indicating the key to be pressed. |
| Procedure | Optional | Variant | A string indicating the name of the procedure to be run. If Procedure is «» (empty text), nothing happens when Key is pressed. This form of OnKey changes the normal result of keystrokes in Microsoft Excel. |
If Procedure is omitted, Key reverts to its normal result in Microsoft Excel, and any special key assignments made with previous OnKey methods are cleared.
Remarks
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, such as a for the character a, or
To specify characters that aren’t displayed when you press the corresponding key (for example: Enter or Tab), use the codes listed in the following table. Each code in the table represents one key on the keyboard.
| Key | Code |
|---|---|
| BACKSPACE | |
| BREAK | |
| CAPS LOCK | |
| CLEAR | |
| DELETE or DEL | |
| DOWN ARROW | |
| END | |
| ENTER (numeric keypad) | |
| ENTER | |
| ESC | < ESCAPE>or |
| HELP | |
| HOME | |
| INS | |
| LEFT ARROW | |
| NUM LOCK | |
| PAGE DOWN | |
| PAGE UP | |
| RETURN | |
| RIGHT ARROW | |
| SCROLL LOCK | |
| TAB | |
| UP ARROW | |
| F1 through F15 | |
You can also specify keys combined with Shift and/or Ctrl and/or Alt and/or Command. To specify a key combined with another key or keys, use the following table.
| To combine keys with | Precede the key code by |
|---|---|
| Shift | + (plus sign) |
| Ctrl | ^ (caret) |
| Alt | % (percent sign) |
| Command | * (asterisk) Only applies to Mac; may only work on Excel 2011 for Mac and not later versions. |
To assign a procedure to one of the special characters (+, ^, %, and so on), enclose the character in braces. For details, see the example.
There is no way to currently detect the Command key in recent versions of Office VBA. Microsoft is aware of this and is looking into it.
Example
This example assigns InsertProc to the key sequence Ctrl+Plus Sign, and assigns SpecialPrintProc to the key sequence Shift+Ctrl+Right Arrow.
This example returns Shift+Ctrl+Right Arrow to its normal meaning.
This example disables the Shift+Ctrl+Right Arrow key sequence.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Выполняет указанную процедуру при нажатии определенной клавиши или сочетания клавиш. Runs a specified procedure when a particular key or key combination is pressed.
Синтаксис Syntax
Expression. OnKey (Ключ, процедура) expression.OnKey (Key, Procedure)
выражение: переменная, представляющая объект Application. expression A variable that represents an Application object.
Параметры Parameters
| Имя Name | Обязательный или необязательный Required/Optional | Тип данных Data type | Описание Description |
|---|---|---|---|
| Key Key | Обязательный Required | String String | Строка, указывающая клавишу для нажатия. A string indicating the key to be pressed. |
| Процедура Procedure | Необязательный Optional | Variant Variant | Строка, указывающая имя выполняемой процедуры. A string indicating the name of the procedure to be run. Если для процедуры задано значение «» (пустой текст), при нажатии клавиши ничего не происходит. If Procedure is «» (empty text), nothing happens when Key is pressed. В этой форме OnKey изменяется нормальный результат нажатия клавиш в Microsoft Excel. This form of OnKey changes the normal result of keystrokes in Microsoft Excel. |
Если процедура опущена, ключ возвращается к нормальному результату в Microsoft Excel, и все специальные сочетания клавиш, выполненные с помощью предыдущих методов OnKey , очищаются. If Procedure is omitted, Key reverts to its normal result in Microsoft Excel, and any special key assignments made with previous OnKey methods are cleared.
Примечания Remarks
Аргумент Key может указывать любой один ключ, объединенный с Alt, CTRL, Shift, или любым сочетанием этих клавиш. The Key argument can specify any single key combined with Alt, Ctrl, or Shift, or any combination of these keys. Каждая клавиша представлена одним или несколькими символами, например a для символа «a» или
Чтобы задать символы, которые не отображаются при нажатии соответствующей клавиши (например: ввод или табуляция), используйте коды, приведенные в следующей таблице. To specify characters that aren’t displayed when you press the corresponding key (for example: Enter or Tab), use the codes listed in the following table. Каждый код в таблице представляет одну клавишу на клавиатуре. Each code in the table represents one key on the keyboard.
| Ключ Key | Код Code |
|---|---|
| BACKSPACE BACKSPACE | |
| BREAK BREAK | |
| CAPS LOCK CAPS LOCK | |
| CLEAR CLEAR | |
| DELETE или DEL DELETE or DEL | |
| СТРЕЛКА ВНИЗ DOWN ARROW | |
| END END | |
| ВВОД (на цифровой клавиатуре) ENTER (numeric keypad) | |
| ВВОД ENTER | |
| ESC ESC | < ESCAPE>или |
| HELP HELP | |
| HOME HOME | |
| INSERT INS | |
| СТРЕЛКА ВЛЕВО LEFT ARROW | |
| NUM LOCK NUM LOCK | |
| PAGE DOWN PAGE DOWN | |
| PAGE UP PAGE UP | |
| RETURN RETURN | |
| СТРЕЛКА ВПРАВО RIGHT ARROW | |
| SCROLL LOCK SCROLL LOCK | |
| TAB TAB | |
| СТРЕЛКА ВВЕРХ UP ARROW | |
| F1–F15 F1 through F15 | |
Кроме того, можно указать ключи в сочетании с клавишами Shift и/или CTRL и/или ALT и/или. You can also specify keys combined with Shift and/or Ctrl and/or Alt and/or Command. Чтобы указать клавишу в сочетании с другой клавишей или клавишами, используйте следующую таблицу. To specify a key combined with another key or keys, use the following table.
| Объединение ключей с To combine keys with | Перед кодом клавиши введите Precede the key code by |
|---|---|
| Смена Shift | + (знак «плюс») + (plus sign) |
| Ctrl Ctrl | ^ (знак «крышка») ^ (caret) |
| Alt Alt | % (знак процента) % (percent sign) |
| Command Command | * символы Применяется только к Mac; может работать только в Excel 2011 для Mac и не более поздних версий. * (asterisk) Only applies to Mac; may only work on Excel 2011 for Mac and not later versions. |
Чтобы назначить процедуру одному из специальных символов (+, ^,% и т. д.), заключите символ в фигурные скобки. To assign a procedure to one of the special characters (+, ^, %, and so on), enclose the character in braces. Дополнительные сведения см. в примере. For details, see the example.
В последних версиях Office VBA невозможно обнаружить ключ команды. There is no way to currently detect the Command key in recent versions of Office VBA. Корпорация Майкрософт знает об этом и ищет ее. Microsoft is aware of this and is looking into it.
Пример Example
В этом примере Инсертпрок назначается сочетание клавиш CTRL + знак «плюс» и назначается СпеЦиалпринтпрок для клавиши Shift + Ctrl + стрелка вправо. This example assigns InsertProc to the key sequence Ctrl+Plus Sign, and assigns SpecialPrintProc to the key sequence Shift+Ctrl+Right Arrow.
В этом примере показано, как вернуть Shift + Ctrl + стрелка вправо к обычному значению. This example returns Shift+Ctrl+Right Arrow to its normal meaning.
В этом примере отключается сочетание клавиш Shift + Ctrl + стрелка вправо. This example disables the Shift+Ctrl+Right Arrow key sequence.
Поддержка и обратная связь Support and feedback
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
I am using the following to run macro «SQL» when I press the enter key.
But, I would like to run macro «SQL» only when in column 1 (column A). Once the macro runs my active cell is in column 9 (column I) and I would like to run a second macro when I press the enter key in this column?
I tried the following, but the macro «SQL» tries to run for both column 1 and column 9?