This should get you started. HTH --Sam
Note -- Before you start, add an Excel Reference to your solution: Solution Explorer - right-click on References - Add - COM Tab - MS Excel Obj Lib. Also, before you start, open Excel, Tools-Macros-Security-Trust Tab-Trust Access to Visual Basic Project.
- Dim xlApp As Excel.Application
-
Dim xlBook As Excel.Workbook
-
Dim xlSheet As Excel.Worksheet
-
Dim xlButton As Excel.OLEObject
-
Dim iStartLine As Long
-
xlApp = New Excel.Application
-
xlApp.Visible = True
-
xlBook = xlApp.Workbooks.Add
-
xlSheet = xlBook.ActiveSheet
-
xlButton = xlSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
-
Link:=False, DisplayAsIcon:=False, Left:=30, Top:=20, Width:=72, Height:=24)
-
xlButton.Name = "BtnTest"
-
xlButton.Object.Caption = "Press"
-
With xlBook.VBProject.VBComponents.Item(xlSheet.CodeName).CodeModule
-
iStartLine = .CreateEventProc("Click", "BtnTest") + 1
-
.InsertLines(iStartLine, "Msgbox ""Hi""")
-
End With
-
xlApp.VBE.MainWindow.Visible = False
-