Search code examples
vbavb.netms-wordvstoribbonx

Need code help on calling a macro from a new VTSO addin for Word


I have created a new addin with a ribbon in MVS. On click of button1 I want to run a macro that is stored in a .dotm file in the Startup folder in Word. The .dotm file is called MyMacros and the macro is titled "TableMacro".

The module name in Word is titled NewMacros and the top rows of the macro in Word are:

Sub TableMacro()
`
` TableMacro

I am sure the macro is started with the code below but even this is guess:

Private Sub Button1_Click_1(sender As Obeject, e As RibbonControlEventArgs) Handles Button1.Click
`code to call TableMacro'
End Sub

I know how to write macros but I have no idea the code needed to trigger the macro stored in the MyMacros.dotm file.


Solution

  • To search all global templates, including the Building Block template, from a VSTO add-in, you can use this:

            Dim wApp = Globals.ThisAddIn.Application
            Dim i As Integer, Tmplt As Word.Template = Nothing
            For i = 1 To wApp.Templates.Count
                If wApp.Templates(i).Name = "MyMacros.dotm" Then
                    Tmplt = wApp.Templates(i)
                    wApp.Run(Tmplt.Name & "!TableMacro")
                End If
            Next
    

    The value of performing it this way is you now have an object variable set to a specific global template and you can then get at AutoText, Styles, etc. and of course macros that are stored in that specific global template.