I have a C# Excel Add-in project \"MyExcelAddIn\" that has a public method Foo() to do something complex. For testing purposes, the add-in also defines a toolbar button whic
I'm using the SendMessage Win32 API to do this. My C# Add-in creates a "NativeWindow" with a uniqe window title that the WinForm app can locate.
For anyone else who finds this here's what I did:
object addInName = "AddinName";
var excelApplication = (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
COMAddIn addIn = excelApplication.COMAddIns.Item(ref addInName);
addIn.Object.AddinMethodName(params);
Also had to add a reference to Microsoft.Office.Core under COM and Excel.Interop under Assemblies.
If you're building an application-level add-in, I believe this may be your answer: MSDN VSTO Article
It involves two steps: (From the article)
The other solution may be: (Again from the article)
I assume that your method Foo somehow interacts with Excel. Otherwise you can just add a reference to the assembly containing the class with the Foo method and call it from there without instantiating Excel.
The only other way I can think is to get a reference to your CommandBarButton through the excelApp object. CommandBarButton has a method called Execute which is similar to clicking the button. Something like this:
Excel.Application excelApp = new Excel.Application();
CommandBarButton btn = excelApp.CommandBars.FindControl(...) as CommandBarButton;
btn.Execute();