View Single Post
 
Old 03-31-2013, 12:51 PM
AlexR AlexR is offline Windows XP Office 2007
Novice
 
Join Date: Mar 2013
Location: Eastern PA, USA
Posts: 8
AlexR is on a distinguished road
Default Is it possible to bind macros to keys not in the KeyCodeConstants class?

Hello all,

I'm trying to bind a macro to certain keys in Word, and I'm having trouble with keys that aren't in the KeyCodeConstants class.

For starters, I had trouble even finding out what the codes were, but I created a textbox in a userform and used the following code to get 63 for the "?" key:
Code:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
MsgBox KeyAscii
End Sub
Next I attempted to bind the space bar (as an experimental control) and the "?" with the following code:
Code:
private sub yes
    msgbox "yes"
end sub
 
Sub SetBindings()
    CustomizationContext = NormalTemplate
    KeyBindings.Add KeyCode:=BuildKeyCode(32), KeyCategory:=wdKeyCategoryMacro, Command:="yes"
    KeyBindings.Add KeyCode:=BuildKeyCode(63), KeyCategory:=wdKeyCategoryMacro, Command:="yes" 
end sub
The end result is that the spacebar triggers the "yes" msgbox but the "?" does not. I conclude from this that either the "?" cannot be bound to a macro or I did something screwy. Can anyone confirm?

Within the context of my project, this would mean that I can only trigger my macro with the spacebar. The problem is that I need to check the word before the spacebar for errors against Word's internal spell check collection. This works fine when there's no punctuation, but in the case of any punctuation, the macro proceeds as though the word was spelled correctly. Here's the code for the actual macro (modified from code I found here: http://www.vbaexpress.com/kb/getarticle.php?kb_id=204)

Code:
Sub CheckLastWord()
    Dim errorCount As Object
     ' Insert a space since this macro bound to the spacebar
    Selection.TypeText Text:=" "
     ' Select word just typed including space with cursor to left of word
    Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
     ' Set errorCount to count errors in selected text
    Set errorCount = Selection.Range.SpellingErrors
     ' move cursor to the right of word just typed
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    If errorCount.Count > 0 Then
        MsgBox "Wrong"
         ' select the word just typed ready for retyping
        Selection.MoveLeft Unit:=wdWord, Count:=1, Extend:=wdExtend
    End If
End Sub
I could use some suggestions as to how to get around the punctuation issue. Perhaps I could use an If statement to skip over the punctuation mark, but I'm not sure how that would work. Obviously I'm not a programmer, and I'm just hacking my way through this. I appreciate the help!
Reply With Quote