Hi,
Imports Office = Microsoft.Office.Core
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim oExcel As Excel.Application
Dim oBook As Excel.Workbook
Dim oModule As VBIDE.VBComponent
Dim oCommandBar As Office.CommandBar
Dim oCommandBarButton As Office.CommandBarControl
Dim sCode As String
' Create an instance of Excel, and show it to the user.
oExcel = New Excel.Application()
' Add a workbook.
oBook = oExcel.Workbooks.Add
' Create a new VBA code module.
oModule = oBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule)
sCode = "sub VBAMacro()" & vbCr & _
" msgbox ""VBA Macro called"" " & vbCr & _
"end sub"
' Add the VBA macro to the new code module.
oModule.CodeModule.AddFromString(sCode)
Try
' Create a new toolbar, and show it to the user.
oCommandBar = oExcel.CommandBars.Add("VBAMacroCommandBar")
oCommandBar.Visible = True
' Create a new button on the toolbar.
oCommandBarButton = oCommandBar.Controls.Add(Office.MsoControlType.msoControlButton)
' Assign a macro to the button.
oCommandBarButton.OnAction = "VBAMacro"
' Set the caption of the button.
oCommandBarButton.Caption = "Call VBAMacro"
' Set the icon on the button to a picture.
oCommandBarButton.FaceId = 2151
Catch exc As Exception
MessageBox.Show("VBAMacroCommandBar already exists.", "Error")
End Try
oExcel.Visible = True
' Set the UserControl property so that Excel does not shut down.
oExcel.UserControl = True
' Release the variables.
oCommandBarButton = Nothing
oCommandBar = Nothing
oModule = Nothing
oBook = Nothing
oExcel = Nothing
' Force garbage collection.
GC.Collect()
End Sub
Add the following code to the top of Form1.vb:Imports Office = Microsoft.Office.Core
Imports Microsoft.Office.Interop
Imports VBIDE = Microsoft.Vbe.Interop