I found this code online and tweaked it a bit for my need to programmatically add a command button to a spreadsheet and assign an event to it. It works well
Sub AddComm_button()
Set mybutton = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Left:=126, Top:=96, Width:=126.75, Height:=25.5)
mybutton.Name = "abcbutton"
Call Modify_CommButton
End Sub
Sub Modify_CommButton()
Dim LineNum As Long 'Line number in module
Dim SubName As String 'Event to change as text
Dim Proc As String 'Procedure string
Dim EndS As String 'End sub string
Dim Ap As String 'Apostrophe
Dim Tabs As String 'Tab
Dim LF As String 'Line feed or carriage return
Ap = Chr(34)
Tabs = Chr(9)
LF = Chr(13)
EndS = "End Sub"
SubName = "Private Sub abcbutton_Click()" & LF
Proc = Tabs & "MsgBox " & Ap & "Testing " & Ap & LF
Proc = Proc & "End Sub" & LF
Set ModEvent = ActiveWorkbook.VBProject.VBComponents("Sheet1").CodeModule
With ModEvent
LineNum = .CountOfLines + 1
.InsertLines LineNum, SubName & Proc & EndS
End With
End Sub
The following code appends my original program with this
Private Sub abcbutton_Click()
MsgBox "Testing "
End Sub
and hence giving it a click event. How to I remove the appended part after my program is done. Right now when I run my program the second time, it already has the method abcbutton_Click() in it and it throws an error.
Thanks Original Source : http://www.mrexcel.com/archive/VBA/5348a.html
End If, just FYI.