Hi friends,
a long time ago I was looking for how to do this today I bring a simple code that maybe can help someone looking for the same
a long time ago I was looking for how to do this today I bring a simple code that maybe can help someone looking for the same
Code
Imports Microsoft.Office.Interop
Imports Microsoft.Vbe.Interop
Imports System.Runtime.InteropServices
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
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_MSForm)
Dim vbComponent As VBComponent = vbProject.VBComponents.Add(vbext_ComponentType.vbext_ct_Document)
'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:\Users\Jod Steivant\Desktop\vbs\geradormacroexcell\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
End Sub
End Class

