Call Outlook VBA code from c#

倖福魔咒の 提交于 2019-12-01 22:43:26

I don't know why you have your exact issue, I'd assume one or more parameters is incorrect but not sure since I've never done it the way you're trying to do it.

I'd suggest looking at the following article for a complete sample using somewhat different code, that you might be able to reuse in your code: HOW TO: Run Office Macros by Using Automation from Visual C# .NET

I thik you're doing it right, but maybe you don't meet the security requirements! In order to run a macro, the office file needs to be a trusted source! It must be flagged via the Office Security Center or else you won't be able to execute macros. You also need to allow access to the VBA Object via the security center for an external app to call the macros!

I had the same problem, the article from Microsoft (HOW TO: Run Office Macros by Using Automation from Visual C#) doesn't help because it covers only calling Outlook macros from Word, Excel, and Access.

Now I finally found the solution on a French site! It covers sending from Python but works also with C#! French Python code: http://www.developpez.net/forums/d1239845/autres-langages/python-zope/bibliotheques-tierces/pywin32-appeler-macro-outlook/

So I ported it to C# with the function I need (where "FnSendMailSafe" is the macro name in Outlook 2007.

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

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

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

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

System.Runtime.InteropServices.Marshal.ReleaseComObject (otApp);
otApp = null;

GC.Collect();   //Garbage collection.

Enjoy!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!