Hi, in Excel I can use below code to call a function via a shortcut, how can I do exactly in Word? Thanks!
Application.OnKey "{F1}", "functionToCall"
Hi, in Excel I can use below code to call a function via a shortcut, how can I do exactly in Word? Thanks!
Application.OnKey "{F1}", "functionToCall"
Re: VBA Word: how to call a function via shortcut key
With difficulty - Application.OnKey is not available in Word and there is no equivalent.
What you can do is run a macro that binds a keystroke to a procedure. Much the same thing as Application.OnKey, I suppose, just not as useful
Try the following:
Paste, in a new module, in the VBA editor for a document
Sub AddBinding()
With Application
'// Refer to THIS document for customisations
.CustomizationContext = ThisDocument
'// Add keybinding: Alt+\
.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyBackSlash), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="TestKeyBound"
End With
End Sub
'// Test keybinding
Sub TestKeyBound()
MsgBox "It works...", vbInformation, "Hey"
End Sub
Display More
The keys are limited to those defined in the Word.WdKey enumeration (Press Shift-F2 with the cursor on wdKeyBackSlash to open the Object Browser and get a list of defined keys).
You can use Alt, Ctrl (and probably Shift - I've never tried), but no combinations, like Alt-Shift + key, areallowed, AFAIK. I'd be happy to be corrected on that.
Don’t have an account yet? Register yourself now and be a part of our community!