Connecting Tech Pros Worldwide Forums | Help | Site Map

Using vb.net to dynamically create excel activeX controls

Newbie
 
Join Date: Mar 2007
Posts: 1
#1: Mar 9 '07
Using VB.net, i want to dynamically create a workbook and add a command botton to one of the sheets. how would i do this. I see example using VBA but i am not able to translate them to Vb.net. Also, after having created the button, how would I be able to defines an event for it (such as the click event). Thanks

SammyB's Avatar
Moderator
 
Join Date: Mar 2007
Location: Springfield, Ohio
Posts: 729
#2: Mar 9 '07

re: Using vb.net to dynamically create excel activeX controls


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.
Expand|Select|Wrap|Line Numbers
  1.         Dim xlApp As Excel.Application
  2.         Dim xlBook As Excel.Workbook
  3.         Dim xlSheet As Excel.Worksheet
  4.         Dim xlButton As Excel.OLEObject
  5.         Dim iStartLine As Long
  6.         xlApp = New Excel.Application
  7.         xlApp.Visible = True
  8.         xlBook = xlApp.Workbooks.Add
  9.         xlSheet = xlBook.ActiveSheet
  10.         xlButton = xlSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
  11.             Link:=False, DisplayAsIcon:=False, Left:=30, Top:=20, Width:=72, Height:=24)
  12.         xlButton.Name = "BtnTest"
  13.         xlButton.Object.Caption = "Press"
  14.         With xlBook.VBProject.VBComponents.Item(xlSheet.CodeName).CodeModule
  15.             iStartLine = .CreateEventProc("Click", "BtnTest") + 1
  16.             .InsertLines(iStartLine, "Msgbox ""Hi""")
  17.         End With
  18.         xlApp.VBE.MainWindow.Visible = False
  19.  
Reply


Similar .NET Framework bytes