Consulting

Results 1 to 5 of 5

Thread: How to call a function via shortcut key?

  1. #1

    How to call a function via shortcut key?

    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"

  2. #2
    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).

  3. #3
    VBAX Wizard
    Joined
    May 2004
    Posts
    6,713
    Location
    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.

  4. #4
    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

  5. #5
    VBAX Wizard
    Joined
    May 2004
    Posts
    6,713
    Location
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •