none
How to add custom menu option in mouse right click event using vba word? RRS feed

  • Question

  • I'm a newbie in visual basic stuffs. I have a requirement like when some words are selected in the document and hit right click ,macro function should be called. Or something like,have to create custom right click menu option in the right click mouse event and when I click that menu option ,macro should be called.

    For example:

    In the document I have four digit numbers like 2001 and 2010. When I select four digit number and hit right click and press my custom menu option,macro should be called and selected four digit no. should be parsed to the macro function which is called.

    How to do it?? I got some code but its for excel, I dont't know how to customize it for microsoft word

    Code for excel:

     
    Const strMacro = "YourCode"
        
        Sub CreateMacro()
           Dim cBut
           Call KillMacro
           Set cBut = Application.CommandBars("Cell").Controls.Add(Temporary:=True)
           With cBut
               .Caption = strMacro
               .Style = msoButtonCaption
               .OnAction = "Test_Macro"
           End With
        End Sub
        
        Sub Test_Macro()
           MsgBox "I work"
        End Sub
        
        Sub KillMacro()
           On Error Resume Next
           Application.CommandBars("Cell").Controls(strMacro).Delete
        End Sub
    




    Monday, December 15, 2014 9:53 AM

Answers

  • Fro Word, it works like this:

    Option Explicit
    Sub CreateMacro()
        Dim MenuButton As CommandBarButton
        With CommandBars("Text")
            Set MenuButton = .Controls.Add(msoControlButton)
            With MenuButton
                .Caption = "Press Me"
                .Style = msoButtonCaption
                .OnAction = "Test_Macro"
            End With
        End With
    End Sub

    Sub Test_Macro()
        MsgBox "I work"
    End Sub

    Sub ResetRightClick()
        Application.CommandBars("Text").Reset
    End Sub

    • Marked as answer by VidhyaRaju Tuesday, December 16, 2014 11:25 AM
    Monday, December 15, 2014 5:47 PM

All replies