Jump to content

VBA: Create command button in userform dynamically and add click event code.

I have tried a lot of approaches. But can't seem to make this work: I'm creating a UI in excel. A cmd-button on sheet1 opens a userform. Another cmd button (in this userform) allows the user to add a row of new fields in the form along with a cmd button to delete the row - if so required. It is this cmd 'delete button' I'm having issues with. The delete buttons are created, and the code inserted into "userform1", but does not execute when I click on the newly created cmd buttons. Here is my code:

Option Explicit
Private Sub UserForm_Initialize()    
    Dim arrNames, arrCaptions As Variant
    Dim NewBtn As Control
    Dim Code As String
    Dim NextLine, LeftPos, Gap, i As Long
    Dim objForm As Object

    Set objForm = ThisWorkbook.VBProject.VBComponents("UserForm1")
    arrNames = Array("cmbName1", "cmbName2", "cmbName3")
    LeftPos = 100
    Gap = 15

    For i = LBound(arrNames) To UBound(arrNames)
        Set NewBtn = UserForm1.Controls.Add("Forms.CommandButton.1")
        With NewBtn
            .Left = LeftPos
            .Top = 5
            .Width = 65
            .Height = 30
            .Name = arrNames(i)
            .Visible = True
            .Caption = "Delete row " & i + 1
            .Font.Size = 10
            .Font.Name = "Times New Roman"
        End With

        'Add the event handler code which does not seem te work at the moment
        'The code is added to "userform1" but does not execute when clicking on the new command buttons
            Code = "Sub " & NewBtn.Name & "_Click()" & vbCrLf
            Code = Code & "     MsgBox ""action for cmd button"" & i" & vbCrLf
            Code = Code & "End Sub"

        With objForm.CodeModule
            'Find last line in Codemodule
            NextLine = .CountOfLines + 1
            .InsertLines NextLine, Code
        End With
        'NEXT button's pos.
        LeftPos = LeftPos + NewBtn.Width + Gap
    Next i
End Sub

Please advise...

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×