VBA - Create button and his event in a classe

edweis

New Member
Joined
Jun 10, 2015
Messages
2
Hello,
Here what i want to do :
I have an userform with juste a frame "Frame1" and a button "Go" outside of it. When i click on this button, it would create a red button inside Frame1 (the more i click on "Go", the more red button comes) and whenever i click on a red button, i would have a MsgBox : "Hey !"

Here is my code :
-------------In the user form : ---------
Code:
    Public a As New gestEvent
    Private i As Integer
    

Private Sub Go_Click()
    Set a = New gestEvent
    Call a.init(Me.Frame1, i)
    i = i + 1
End Sub


Private Sub UserForm_Initialize()
    i = 0
End Sub


In the class "gestEvent" : ----------

Code:
Option Explicit
' Declare object variable as CommandButton.
Private WithEvents cmdObject As CommandButton

Public Sub init(f As frame, i As Integer)
   Set cmdObject = f.Controls.Add("Forms.CommandButton.1", "cmdOne" & i)
   cmdObject.Visible = True
   cmdObject.BackColor = &HFF&
   cmdObject.Top = 20 * i
   cmdObject.Caption = "Dynamic CommandButton"
End Sub

Private Sub cmdObject_Click()
    MsgBox "This is a dynamically added control"
End Sub

My Probleme is that only the last button created has the animation.
do you have any tips ?

Thank you
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Should be:
Rich (BB code):
Private eventHandlers as Collection

Private Sub Go_Click()

    Dim a as gestEvent
    Set a = New gestEvent
    Call a.init(Me.Frame1, eventHandlers.count)
    eventHandlers.Add a

End Sub


Private Sub UserForm_Initialize()
    Set eventHandlers = New Collection
End Sub

Otherwise your event handling object simply gets overwritten
 
Upvote 0

Forum statistics

Threads
1,196,081
Messages
6,013,318
Members
441,760
Latest member
Sharina

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top