C# VSTO for Outlook - Button that triggers a VBA Macro

0

I'm trying to create a custom Ribbon with a button that triggers a VBA Macro in Outlook 2010. Creation of the ribbon itself works fine but the button doesnt trigger the VBA.

I've tried these solutions: 1) How-to: Run existing Word VBA Macros from C# Ribbon Addin but it throws an error since AFAIK Outlook.Application doesn't have a Run() method, contrary to Excel or Word.

public void RunMacro(object otApp, object[] oRunArgs){

        otApp.GetType().InvokeMember("Run",
            System.Reflection.BindingFlags.Default |
            System.Reflection.BindingFlags.InvokeMethod,
            null, oApp, oRunArgs);
    }

        public void RunChronosMacro(Office.IRibbonControl control)
        {
            RunMacro(oApp, new object[] { "TestMacro" })
        }

2) The third answer of this question Call Outlook VBA code from c# but it also throws an exception {"Unknow name. ( RESULT : 0x80020006 (DISP_E_UNKNOWNNAME))"}. Maybe this was working in Outlook 2007 but it doesn't in my environnement. As this answer is inspired from Python code, I've also tried it in Python but without success.

public void RunChronosMacro(Office.IRibbonControl control)
{
    try
    {
        otApp.GetType().InvokeMember("TestMacro",
                    System.Reflection.BindingFlags.Default |
                    System.Reflection.BindingFlags.InvokeMethod,
                    null, otApp, arFunctionParameters);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(otApp);
                    otApp = null;
                    GC.Collect();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.GetType().ToString());
    }

}

I'm quite hard-stuck on this and as I'm not very familiar with C# and Offices add-ins, I don't know what to try next. Thanks in advance for any help.

c#
vba
outlook
vsto
outlook-addin
asked on Stack Overflow Sep 7, 2018 by May.D • edited Jun 23, 2020 by Martijn Pieters

1 Answer

0

Please try the code below:

    using Outlook = Microsoft.Office.Interop.Outlook;
object oMissing = System.Reflection.Missing.Value;

// create outlook object
Outlook.Application otApp = new Outlook.Application();

string[] functionParameters =
            { 
                sTo,
                sCC,
                sBCC,
                sSubject,
                sBody
            };

// Run the macro
otApp.GetType().InvokeMember("YourVBA",
            System.Reflection.BindingFlags.Default |
            System.Reflection.BindingFlags.InvokeMethod,
            null, otApp, functionParameters);

For more information, Please refer the link below:

Need to run/invoke macro from c# code for Outlook Addin

How can I run a macro from a VBE add-in, without Application.Run?

Hopefully it helps you!

answered on Stack Overflow Sep 7, 2018 by Lina • edited Sep 7, 2018 by Lina

User contributions licensed under CC BY-SA 3.0