The only way I know to embed code in a VBA project is to use Office.Interop.Excel along with Microsoft.Vbe.Interop (not sure if ClosedXML and the other third party ... but still want to split)
But since you are asking for an alternative, here is how I will:
Creating a workbook and inserting a macro to it using C#
You need to enable programmatic access to VBA Project in Excel.
- (Excel) File → Settings → Trust Center → Trust Center Settings → Macro Settings → Trust access to the VBA project object model

In your C # solution, add COM links to
Add using directives to your C # code behind the file
using Microsoft.Office.Interop.Excel; using System.Reflection; using Microsoft.Vbe.Interop; using System.Runtime.InteropServices;
Now follow the code and comments
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); xlApp.Visible = true; Workbook wb = xlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet); VBProject vbProj = wb.VBProject; // access to VBAProject VBComponent vbComp = vbProj.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule); // adding a standard coding module vbComp.CodeModule.DeleteLines(1, vbComp.CodeModule.CountOfLines); //emptying it // this is VBA code to add to the coding module string code = "Public Sub HelloWorld() \n" + " MsgBox \"hello world!\" \n" + "End Sub"; // code should be added to the module now vbComp.CodeModule.AddFromString(code); // location to which you want to save the workbook - desktop in this case string fullPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\macroWorkbook.xlsm"; // run the macro xlApp.Run("HelloWorld"); // save as macro enabled workbook wb.SaveAs(Filename: fullPath, FileFormat: XlFileFormat.xlOpenXMLWorkbookMacroEnabled); xlApp.Quit();
In the above code;
you create an application for the Excel host, add a workbook. Open the VBA Project Object module, add a new standard coding module to the VBA project, write a VBA macro to this module. Application.Run("HelloWorld") just calls the macro, you can comment on this section if you do not want the window to pop up. Then at the end you save the book as a book with macro support at the location specified in the fullPath variable.
PS. Please note that I did not add error handling.
For more tips on C # and VBA, see this blog. Hope this helps :)
user2140173
source share