It is possible to run your macros when a particular key or key combination is pressed.
This method can only be used to assign macros to shortcut keys.
This can be done by invoking the OnKey method where 'key' is the key combination and 'procedure' is the name of the macro.
Any key assignments made are applied to all open workbooks and only persist in the current Excel session.


The 'key' can specify any single key or any key combined with one or more of the Alt, Ctrl or Shift keys.

Application.OnKey key, procedure 
Call Application.OnKey(key, procedure)

Call Application.OnKey(key) - restore hotkey assignment to normal 
Call Application.OnKey(key, "") - disables hotkey

Call Application.OnKey("^c", "myMacro") 
Call Application.OnKey("{Up}", "CustomMoveUpMacro")

Normal alphanumeric keys are denoted by themselves (e.g. "a", "A", "1").
It is possible to use special keys as well although these have special codes that must be used.
For a full list of all the special keys that can be used, please refer to the VBA > Macros > Sendkeys page.
In order to use one of the following characters + ^ % { ) ~ without having it interpreted as a special key just enclose it in curley braces.

Call Application.OnKey ("{%}") 

Changing Built-in Behaviour

It is also possible to use this method to change the normal behaviour of Excel by assigning a key combination that Excel uses already by default, such as (Ctrl + S) for save.
We can disable a built-in shortcut key by assigning it to an empty string. The following line of code disables the (Ctrl + S) shortcut key.

Call Application.OnKey ("^o", "") 

To enable the shortcut key back to its original functionality you can use the following line of code.

Call Application.OnKey ("^o") 


The method Application.OnKey does not exist in Word at the moment.


The method Application.OnKey does not exist in PowerPoint at the moment.

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext