This snippet demonstrates how you can add VBA code to an Excel file at run time.
Prerequisites
In this snippet I am using Microsoft Excel 2013 with the Microsoft Excel 15.0 object library.
Before you can use this code, you will have to change a setting within Microsoft Excel to authorise the use of the VBA Project Object Model from external programs. This is a security feature to protect end users from malicious programs and is disabled by default. If you do not enable this feature then the code below will result in an exception stating "Programmatic access to Visual Basic Project is not trusted" as soon as you attempt to reference the VBA environment.
Enabling trust to the VBA Project Object Model
- Open Excel and access the Options section.
- Select the Trust Center section
- Click the Trust Center Settings button
- Select the Macro Settings section
- Tick the box labelled "Trust access to the VBA project object model"
The code
You will need the following Imports statements:
Imports Microsoft.Office.Interop
Imports Microsoft.Vbe.Interop
Imports System.Runtime.InteropServices
Imports System.Text
Then:
Dim excelApplication As New Excel.Application
Dim excelWorkbooks As Excel.Workbooks = excelApplication.Workbooks
Dim excelWorkbook As Excel.Workbook = excelWorkbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet)
Try
'Create a VB Project and add a standard module component
Dim vbProject As VBProject = excelWorkbook.VBProject
Dim vbComponent As VBComponent = vbProject.VBComponents.Add(vbext_ComponentType.vbext_ct_StdModule)
'Your code
Dim codeString As New StringBuilder
codeString.AppendLine("Public Sub SaySomething()")
codeString.AppendLine("MsgBox ""Hello""")
codeString.AppendLine("End Sub")
'Add your code to the standard module component
vbComponent.CodeModule.AddFromString(codeString.ToString)
'Save and quit
excelWorkbook.SaveAs("C:\Temp\MyVBAExcelFile.xlsm", Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled)
Catch ex As Exception
MessageBox.Show(ex.Message, "Exception Details", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Finally
excelApplication.Quit()
Marshal.ReleaseComObject(excelWorkbooks)
Marshal.ReleaseComObject(excelWorkbook)
Marshal.ReleaseComObject(excelApplication)
End Try