I wrote a small example in which it adds a new button to an existing book, and then adds a macro that will be called when the button is clicked .
using Excel = Microsoft.Office.Interop.Excel; using VBIDE = Microsoft.Vbe.Interop; ... private static void excelAddButtonWithVBA() { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE"); Excel.Worksheet wrkSheet = xlBook.Worksheets[1]; Excel.Range range; try {
And here we got the buttonMacro(..) method
private static void buttonMacro(string buttonName, Excel.Application xlApp, Excel.Workbook wrkBook, Excel.Worksheet wrkSheet) { StringBuilder sb; VBIDE.VBComponent xlModule; VBIDE.VBProject prj; prj = wrkBook.VBProject; sb = new StringBuilder(); // build string with module code sb.Append("Sub " + buttonName + "_Click()" + "\n"); sb.Append("\t" + "msgbox \"" + buttonName + "\"\n"); // add your custom vba code here sb.Append("End Sub"); // set an object for the new module to create xlModule = wrkBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule); // add the macro to the spreadsheet xlModule.CodeModule.AddFromString(sb.ToString()); }
Found this information in an article in KB How to create an Excel macro using automation with Visual C # .NET
source share