(Solved) – Create a Series of dynamically created button by clicking each of them in Excel VBA

(solved)-–-create-a-series-of-dynamically-created-button-by-clicking-each-of-them-in-excel-vba

Please don’t consider this question as a repeated question! This
question is clearly different from earlier similar-looking queries.

Last few days, I’m practicing a class module in Excel VBA.

I have presented myself a very simple looking task but it turned out like a champ!

My task is very simple!

Challange

I have a BLANK Userform inserted manually! From now, no controls will be added manually.

As soon as you initialize the Userform, it should appear with one single CommandButton on the Top-Left corner of the form.

Now, Click on the button and you will be server another CommandButton right-below of the button! And so, click on the newly created button and another button will be created again right below of the previous button and the process keep going on as long as you keep clicking on the newly created CommandButtons.

Problem I’m facing

I’m able to create the First button on the Userform when it was initialized and also able to create a new button below of it. But Nothing after that. Nothing happens when I’m clicking on the second/newly created button.

Here is my Userform Code

Dim A As New Class2       ' Create an object of the Class (where we declared the events).

Private Sub UserForm_Initialize()

    ' Create and add the button control.
    Dim btEx As MSForms.CommandButton
    Set btEx = UserForm1.Controls.Add("Forms.CommandButton.1")

    With btEx
        .Top = 12
        .Left = 12
        .Width = 72
        .Height = 36
        .Caption = "Click Me"
    End With

    Set A.btEvents = btEx

End Sub

Here is the Class Module

Public WithEvents btEvents As MSForms.CommandButton

Private Sub btEvents_click()

    ' Create and add the button control.
    Dim btEx As MSForms.CommandButton
    Set btEx = UserForm1.Controls.Add("Forms.CommandButton.1")

    With btEx
        .Top = 30
        .Left = 30
        .Width = 72
        .Height = 36
        .Caption = "Click Me"
    End With

End Sub

Need your insights or help to understand am I going in the right way? I’m not able to assign the event to the dynamically created CommandButton from the class module.

Please let me know, am I missing something or it’s not even possible in the platform? I’m really a kind of a newbie in Excel VBA Class Module programming.

Thank you in advance.

Leave a Reply

Your email address will not be published. Required fields are marked *