Hello,
I want to add new buttons to an existing userform at runtime and link event handler to them so that the buttons do something.
I've tried several ways that I've found online and managed to create the button and to programmatically add the code for the click event but when i click the button nothing happens. The button and click event sub code is created fine.
I have added the reference to Microsoft VBA Extensibility but something is missing.
Please, I am completely stuck and would appreciate any help! Thank you.
Here's the code I have so far:
Dim myCmdObj As CommandButton
Dim i As Integer
Private Sub CommandButton1_Click()
Dim NName As String
i = i + 1
' Set the name for the button
NName = "cmdAction" & i
' Add button
Dim N As Long
Set myCmdObj = frmMain.Controls.Add("Forms.CommandButton.1", NName, Visible)
With myCmdObj
.Caption = NName
.Left = 20 * i
.Width = 20
.Top = 20
End With
' Inserts code for the button
With ThisWorkbook.VBProject.VBComponents(5).CodeModule
N = .CountOfLines
.InsertLines N + 1, "Private Sub " & NName & "_Click()"
.InsertLines N + 2, vbNewLine
.InsertLines N + 3, vbTab & "lblTest.Caption = ""BUTTON CLICKED"""
.InsertLines N + 5, "End Sub"
End With
End Sub
Please help me!!