1) Here is the code I use that works for Excel using the .Net reference: Microsoft.Office.Interop.Excel v14 (not the ActiveX COM Reference):
using System;
using Microsoft.Office.Interop.Excel;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
RunVBATest();
}
public static void RunVBATest()
{
Application oExcel = new Application();
oExcel.Visible = true;
Workbooks oBooks = oExcel.Workbooks;
_Workbook oBook = oBooks.Open("C:\\temp\\Book1.xlsm");
// Run the macro.
RunMacro(oExcel, new Object[] { "TestMsg" });
//Run a macro with parameters
//RunMacro(oExcel, new Object[] { "ShowMsg", "Hello from C# Client", "Demo to run Excel macros from C#" });
// Quit Excel and clean up
oBook.Saved = true;
oBook.Close(false);
oExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
}
private static void RunMacro(object oApp, object[] oRunArgs)
{
oApp.GetType().InvokeMember("Run",
System.Reflection.BindingFlags.Default |
System.Reflection.BindingFlags.InvokeMethod,
null, oApp, oRunArgs);
}
}
}
}
2) make sure you put the Macro code in a Module (a Global BAS file)..
Public Sub TestMsg()
MsgBox ("Hello Stackoverflow")
End Sub
3) make sure you enable Macro Security and Trust access to the VBA Project object model:
