I am trying to write some codes to place a button into my worksheet automatically and when click on the button it will execute some codes. I wrote my code based on the example I saw from the book "Excel 2013 Power Programming with VBA" (p896). I am using Excel 2007 though not sure if it matters. Anyways, I modified the codes to below:
*Sub AddButtonAndCode()
Dim NewButton As OLEObject
Dim NewSheet As Worksheet
Set NewSheet = Worksheets("Sheet1")
Set NewButton = NewSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Left:=5, Top:=5, Height:=25, Width:=100)
Code = "Sub CommandButton1_Click()" & vbCrLf
Code = Code & " MsgBox ""???""" & vbCrLf
Code = Code & "End Sub"
With ActiveWorkbook.VBProject.VBComponents(NewSheet.Name).CodeModule
NextLine = .CountOfLines + 1
.InsertLines NextLine, Code
End With
End Sub*
It works for the button part, but after I added the parts below defining the button, it gives me error "Subscript out of range"
Could anybody help me to figure out what's wrong in there?
Thank you very much!