Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to: Run existing Word VBA Macros from C# Ribbon Addin

Tags:

c#

ms-word

vba

vsto

Background: I have an extensive set of specialized VBA macros used in Word for document formatting purposes. In Word 2003, these macros were activated from a customized toolbar. I have recently transitioned to Word 2007 and would like to be able to run these existing VBA macros from a new Word Ribbon created with VS 2010. I have created a Ribbon; however, I cannot figure out how to call the existing macros from the new Ribbon buttons.

Question: How do I call the existing VBA macros, which are stored in a .dotm template, from the C# Word Add-in?

Any help would be greatly appreciated.

like image 345
BlueDevil Avatar asked Nov 14 '09 22:11

BlueDevil


People also ask

How do I run a VBA macro in Word?

Choose “Macros” and click “Add” to the toolbar after selecting “All Commands” from the “Choose commands from” drop down list. Then click “Ok” to close the window. Back to the document, you can find the macro is already in the Quick Access Toolbar. Therefore, you can easily click it to run your code.

How do I run VBA code in Automation Anywhere?

You can store your Macro. xlsxm file to AA My Docs folder and pass your excel file name (on which you want to perform macro operation) and path to your macro. You need to configure your Macros file and as per the requirement tool has to pass the file path and name as parameter in Run excel macros command.


1 Answers

The technique described in MS KB article 306683 -- in particular, function RunMacro defined there -- should allow you to call a VBA macro from within C# code: You define a function RunMacro

private void RunMacro(object oApp, object[] oRunArgs)
{
    oApp.GetType().InvokeMember("Run",
        System.Reflection.BindingFlags.Default |
        System.Reflection.BindingFlags.InvokeMethod,
        null, oApp, oRunArgs);
}

and then call your macro like this:

RunMacro(oApp, new object[] {"NameOfMyMacro"})

or

RunMacro(oApp, new object[] {"NameOfMyMacro", "some", 3, "parameters"})

oApp is the Word.Application object, which I'm sure is available somewhere in a Word add-in.

like image 55
Heinzi Avatar answered Nov 13 '22 13:11

Heinzi