Error: "Document_KeyUp" event not working

48 Views Asked by At

I'm trying to change the color of the text I'm going to type every time the " key is pressed in my current word document. But the key Up event doesn't seem to work, I even put a MsgBox in it to see Yes it was the key code and nothing.

Note: The document is enabled for macros and in security options allows all macros to run.

Note: I use Office 2013

This is my code:

Private Sub Document_KeyPress(ByVal KeyCode As Integer, ByVal Shift As Integer)
    Static Is_Str As Boolean
    
    If KeyCode = 34 Then
        ' The key was pressed "
        If Is_Str Then
            ' End Str
            Selection.Font.Color = RGB(0, 0, 0)
        Else
            ' Init Str
            Selection.Font.Color = RGB(0, 255, 0)
        End If
        Is_Str = Not Is_Str
    End If
    'I put this in to make sure that if the function is called when a key is pressed
    MsgBox "A key has been pressed"
End Sub

This is the structure of my project: enter image description here

And how I want it to be executed: enter image description here

Question translated from Spanish:

1

There are 1 best solutions below

4
Black cat On

The resolve for this issue needs to create a Class with the WindowSelectionChange event.

Insert a Class module the name will be Class1 with this code

Public WithEvents myclass As Word.Application


Private Sub myclass_WindowSelectionChange(ByVal Sel As Selection)
MsgBox "A button was pressed"
End Sub

In the ThisDocument modul insert this:

Dim X As New Class1
Sub init()
Set X.myclass = Word.Application
End Sub

After running this sub the event will be invoked if you change the selection on the word document even if repositioning the cursor.

Microsoft documentation:

(https://learn.microsoft.com/en-us/office/vba/api/word.application.windowselectionchange)

and

(https://learn.microsoft.com/en-us/office/vba/word/concepts/objects-properties-methods/using-events-with-the-application-object-word)