View Full Version : [SLEEPER:] How to call a function via shortcut key?
brendaburgos
08-03-2012, 03:42 AM
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"
Jay Freedman
08-04-2012, 05:27 PM
The Application object in Word doesn't have an OnKey method. Instead, you assign a KeyBinding. From the Help topic on the Application.KeyBindings collection:
This example assigns the CTRL+ALT+W key combination to the FileClose command. This keyboard customization is saved in the Normal template.
CustomizationContext = NormalTemplate
KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyControl, wdKeyAlt, _
wdKeyW), KeyCategory:=wdKeyCategoryCommand, _
Command:="FileClose"
If memory serves, you cannot reassign the keybinding for the F1 key because that's required to be Help.
The macro name goes in the quotes assigned to the Command parameter. It must be a Sub and not a Function (because there's no way to pass an argument to the function or return a value from the function).
fumei
08-04-2012, 06:47 PM
Just to make it fully disclosed...
CustomizationContext can be: Normal template, ActiveDocument or ActiveDocument.AttachedTemplate
In other words you can not set a keybinding to an UNactive document. It can be set for one of Normal.dot, the template of the active document, or the active document itself.
brendaburgos
08-05-2012, 03:00 AM
Thanks a lot!
As I always use F1 button in my Office macros, I will set the keybinding to F1 to ThisDocument to make it not affecting other documents.
With Application
.CustomizationContext = ThisDocument
.KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyF1), _
KeyCategory:=wdKeyCategoryCommand, _
Command:="printAllRecords"
End With
fumei
08-05-2012, 04:36 PM
As I always use F1 button in my Office macros,
For the reason Jay mentions, this is not that great an idea. Why do you want to use F1? F1 calling an application Help is a standard. Generally speaking altering a standard is poor design. especvially since there are so many other combinations.
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.