Referred This:
And used xlUDF and xlcRun but got error "Can not run the macro TestMacro..." ( I created TestMacro in Excel sheet to call Userform)
Then found this and realized that Macro call won't work directly from C# method assigned to ribbon's button
So created a another class with a Function to call Macro, which works !!!
My current code
//Code for calling Macro defined inside excel's module
public class InterfaceFunctions
{
public String openUserForm()
{
String msg = "Error is: ";
try
{
dynamic xlApp = ExcelDnaUtil.Application;
xlApp.Workbooks["Book1.xlsm"].Activate();
xlApp.Run("TestMacro");
}
catch (Exception ex)
{
msg = msg + ex;
return msg;
}
msg = null;
return msg;
}
}
And Function which is called by ribbon button
public static void addDatatToSheet()
{
Microsoft.Office.Interop.Excel.Application Application = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;
Worksheet sheet1Ws = Application.Worksheets["Sheet1"] as Worksheet;
sheet1Ws.Cells[1,4].Value2 = null;
//XlCall.Excel(XlCall.xlUDF, "TestMacro"); dosen't work
//XlCall.Excel(XlCall.xlcRun, "TestMacro"); dosen't work
try
{
InterfaceFunctions instance = new InterfaceFunctions();
String result = instance.openUserForm();
if (result!=null)
{
MessageBox.Show(result);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
Now the questions are:
1. Is this the right approach?
2. Is there a way I can get sheet name from button (ie addDatatToSheet Function) itself rather than hardcoding in openUserForm function.
Regards,
Ankit