How do I add a Macro to an Excel Sheet using Late Binding?
I had the code working using Excel(2010) PIA:
//create a new VBA control module
oModule = oWorkbook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
//Add the VBA macro to the new code module
oModule.CodeModule.AddFromString(sCode) //sCode is the VBA macro I created;
I now have to support multiple versions of Excel so I have to use Late Binding.
I have been able to create an Excel Worksheet and populate it.
All I have left to do is add a macro to a work book.
Code creating Excel Worksheet:
objClassType = Type.GetTypeFromProgID("Excel.Application");
oExcelObject = Activator.CreateInstance(objClassType);
//Get the workbooks collection
oWorkbooksObject = oExcelObject.GetType().InvokeMember("Workbooks",
BindingFlags.GetProperty, null, oExcelObject, null);
//Add a Workbook;
oWorkbookObject = oWorkbooksObject.GetType().InvokeMember("Add",
BindingFlags.InvokeMethod, null, oWorkbooksObject, null);
//Get the Worksheets collection and the first Worksheet
Parameters = new object[1];
Parameters[0] = 1;
oWorksheetsObject = oWorkbookObject.GetType().InvokeMember("Worksheets",
BindingFlags.GetProperty, null, oWorkbookObject, null);
oWorksheetObject = oWorksheetsObject.GetType().InvokeMember("Item",
BindingFlags.GetProperty, null, oWorksheetsObject, Parameters);