Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Onkey not run for a left parenthesis?

Tags:

macos

excel

vba

The following code line runs:

Application.OnKey “&”, “macro name”

But this line

Application.OnKey “(“, “macro name”

causes runtime error 1004:

Application-defined or object-defined error

Why? The only difference is the character. I'm using Excel on a Mac.

like image 845
Steve Avatar asked Dec 13 '25 03:12

Steve


1 Answers

It seems that for whatever reason brackets are considered to be special characters, to use them to trigger the Application.OnKey you have to put them inside curly braces:

Sub SetupKeyBindings()
    Application.OnKey "{(}", "TestMacro"
    Application.OnKey "{)}", "TestMacro"
    MsgBox "Key bindings set. Try pressing Shift+9/0 to run the macro."
End Sub

Sub TestMacro()
    MsgBox "TestMacro was triggered!"
End Sub

Instead of curly braces you can also use Application.OnKey "+9" for Shift-9

Edit, you can also use key codes with the curly braces ("{key_code}"), the full list can be found here.

For example Application.OnKey "{106}" captures the numpad multiplication sign as opposed to the normal multiplication sing (Shift-8).

like image 108
Michal Rosa Avatar answered Dec 15 '25 18:12

Michal Rosa