OnKey Method

An OnKey event handler runs when the user presses a specified key combination. To associate a procedure with a specified key combination, use the procedure argument to the OnKey method of the Application object. Unlike many of the other OnEvent handlers, the OnKey handler does run if you simulate sending keystrokes to Microsoft Excel under program control. You would use the SendKeys method to do this.

The following code runs the DoReports procedure when the user presses F12.


Sub TrapKeys()                            'Trap key combinations.
    Application.OnKey _
        key := "{F12}" , _
        procedure := "DoReports"
End Sub

Sub DoReports()                            'F12 OnKey handler.
    AssembleReports
    PrintReports
End Sub

For a complete list of special codes for key combinations, see "OnKey method" in Help.

Note

The OnKey event handler doesn't run if its associated key combination is pressed while another procedure is running. Therefore, you cannot use an OnKey handler if you want to run a special procedure when the user presses Esc to stop the currently running procedure. You can, however, use the EnableCancelKey property to modify the behavior of the Esc key. For more information, see "EnableCancelKey property" in Help.