Home > Blockchain >  Excel Error on Application.OnKey Statement
Excel Error on Application.OnKey Statement

Time:12-30

I put this simple code into Visual Basic:

Sub HelloWorld()
MsgBox "Hello World"
End Sub

Sub OnKeyDemo()
Application.OnKey "^ a","HelloWorld"
End Sub

When I press CTRL SHIFT A on the Workbook, I get the following error: enter image description here

I enabled all macros on Excel and I did a Step Into procedure recommended by others on StackExchange. Neither have worked.

Thanks!

CodePudding user response:

You are getting this error because the Application.OnKey is not able to find the HelloWorld subroutine.

Microsoft's documentation does not have clear information regarding where the procedure should reside, in the general module or worksheet/workbook module.

I have tried and tested by adding this procedure in the workbook/worksheet and general module. It only works in the General Module

To add a general module: Open the Project Explorer (Ctrl R) and right-click on any item. Then Select Insert->Module

In the general module add the Sub HelloWorld() procedure and it will definitely work.

Very Important

Reverse the OnKey Statement as not doing this may cause unexpected results.

For Doing this follow the below steps:

  1. Go to the ThisWorkbook Code Pane
  2. Above the code pane you will find two dropdowns, select Workbook in first and BeforeClose in the second.
  3. In the added code for BeforeClose, write Application.OnKey "^ a", note the lack of ,"HelloWorld".

Omitting the ,"HelloWorld" is fine since the second parameter for the Application.OnKey procedure is optional.

What Application.OnKey "^ a" does is resets the previously assigned key binding to the HelloWorld procedure.

I hope that I have been of help.

  • Related