Link to home
Start Free TrialLog in
Avatar of quizzer
quizzer

asked on

Assign Keyboard shortcut to Word Sub via code

I have a sub below that I want the users to be able to execute in the document by a Keyboard Shortcut Alt Q.  I know how to assign this using Tools Customize Keyboard, but is there a way to assign that shortcut in the Sub itself via code?  Thanks


Sub Insert_Data()
Selection.TypeText Text:="THIS IS TEXT TO INSERT RIGHT HERE"
Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Font.Color = wdColorBlack
Selection.Font.Bold = True
Selection.HomeKey Unit:=wdLine

End Sub
ASKER CERTIFIED SOLUTION
Avatar of Chris Bottomley
Chris Bottomley
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of quizzer
quizzer

ASKER

Chris,
Thanks for responding.  So if for example I wanted to change the keyboard shortcut from Alt Q to Alt K all I would have to do is change the Q to K like below in the code, without needing to go in and assign the keysthrough Tools Customize Keyboard/

Sub Bind_Shortcuts()
Dim bound As KeyBinding
    Set bound = Application.FindKey(BuildKeyCode(wdKeyK, wdKeyAlt))
    If bound.Command = "" Then
        KeyBindings.Add wdKeyCategoryMacro, "Insert_Data", BuildKeyCode(wdKeyK, wdKeyAlt)
    Else
        bound.Rebind wdKeyCategoryMacro, "Insert_Data", BuildKeyCode(wdKeyK, wdKeyAlt)
    End If
   
Set bound = Nothing
End Sub
Yup and similarly for wdkeyshift, wdkeycontrol combinations i.e:

BuildKeyCode(wdKeyK, wdKeyAlt, wdKeyControl)

would mean the ctrl alt K key combination

Chris
Avatar of quizzer

ASKER

Tried This Using Alt K and it doesn't work.  Any ideas???

Sub Bind_Shortcuts()
Dim bound As KeyBinding
    Set bound = Application.FindKey(BuildKeyCode(wdKeyAlt, wdKeyK))
    If bound.Command = "" Then
        KeyBindings.Add wdKeyCategoryMacro, "Insert_Data", BuildKeyCode(wdKeyAlt, wdKeyK)
    Else
        bound.Rebind wdKeyCategoryMacro, "Insert_Data", BuildKeyCode(wdKeyAlt, wdKeyK)
    End If
   
Set bound = Nothing
End Sub
Sub Insert_Data()
'
' Insert_Data Macro
' Macro recorded 11/14/2007 by David Vessey



Selection.TypeText Text:="THIS IS TEXT TO INSERT RIGHT HERE"
Selection.HomeKey Unit:=wdLine
Selection.EndKey Unit:=wdLine, Extend:=wdExtend
Selection.Font.Color = wdColorBlack
Selection.Font.Bold = True
Selection.HomeKey Unit:=wdLine

End Sub
Avatar of quizzer

ASKER

I figured it out.  You have to run the Sub
Bind_Shortcuts

when the Document Opens in order for the shortcut you designate to be available.
Can you give any clues ... i've double checked and all works fine in that that the binding works fine.

Chris
Sorry ... didn't realise the general situation.  Yes you are absolutely right it needs to be run on open for any using document.

Chris