PDA

View Full Version : Assigning a key combination to a macro by code



Saquiwej
10-28-2006, 10:58 AM
A have a macro, that I would like to run by pressing two keys of my keyboard simultaneously , for example Alt+Enter, because it is so convenient. Ideally this shortcut would be ?alive? only while I am working with a certain document, on closing the document it should be cancelled, for in other macros I use the same shortcut for different purposes. In Excel I used the OnKey statement for watching keystrokes. Interestingly enough in Word OnKey doesn?t work. Instead there is a much more complex way to assign keystroke combinations to macros. My code is like this:



Sub hidereveal()
Dim hidrange As Range
CustomizationContext = ActiveDocument
KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyReturn), KeyCategory:=wdKeyCategoryMacro, _
Command:="revrange"
Set hidrange = ActiveDocument.Range(Start:=Selection.End, End:=ActiveDocument.Range.End)
hidrange.Font.Color = RGB(160, 160, 164)
ActiveDocument.Range(Start:=0, End:=Selection.End).Font.Color = wdColorAutomatic
End Sub

Lines 3 and 4 are relavant to my question. When I run the macro invariably I get a run-time error nr ?5346? and the message: The function assigned to the specified key cannot be modified. I tried different key combinations, or single keys, but could not find any that would not trigger the same run-time error. Can anyone help me with this issue. I have reached the point where I have no more ideas.

mdmackillop
10-31-2006, 11:57 AM
If you save your code in a module within the Document, and also save your shortcut there, it would then be usable as you require

fumei
10-31-2006, 12:22 PM
I am not sure what the problem is. I can get it to work.Option Explicit

Sub NewTest()
MsgBox "Hello"
End Sub

Sub Whatever()

CustomizationContext = ActiveDocument
KeyBindings.Add KeyCode:=BuildKeyCode(wdKeyAlt, wdKeyReturn), _
KeyCategory:=wdKeyCategoryMacro, _
Command:="NewTest"

End Sub I used this as the stuff with the Range is not - or shouldn't be - relevant to the issue.

I ran the Whatever Sub. Alt-Enter now fires the Sub NewTest, and the message is displayed.

Alt-Enter, BTW, is the built-in default Word key combination for ReDo.

Not only that, both Subs above are in Normal.dot. I fired it, then saved the current document. The Alt-Enter (to display "Hello") key combination is only available in that document. In any other document Alt-Enter acts like normal...it fires ReDo.

Saquiwej
11-01-2006, 03:29 AM
Thank you for your replies. I have learnt new things from them, the solution to my problem was much more simple, though. I simply mistyped the called procedure. The keybinding command works allright. It was a human mistake this time.

fumei
11-01-2006, 11:47 AM
Question: are you using Option Explicit?

Saquiwej
11-04-2006, 06:48 AM
Yes, I always use option exlicit. It helps you with variables, but not with mistyped procedure names, as far as I know.