How to make the relatively same event code to multiple generated userform controls?
I have made a userform pre-start that creates command buttons off a list from another sheet after initialize. The idea right now is to put the stored caption of the userform control I click on the active cell. Right now I can only add a event sub on the one that is already on the userform. How can I add the same event code that I applied to every command button that is generated? Here is the code so far, including the click event sub:
Option Explicit
Dim Genre(0 To 20) As msforms.CommandButton
Private Sub UserForm_Initialize()
Dim i As Integer
Dim Genre(0 To 20) As msforms.CommandButton
i = 0
Do
Set Genre(i) = Me.Controls.Add("Forms.CommandButton.1")
With Genre(i)
.Width = Me.Controls("Unknown").Width
.Height = Me.Controls("Unknown").Height
.Left = Me.Controls("Unknown").Left
.Top = Me.Controls("Unknown").Top + Me.Controls("Unknown").Height * (i + 1)
.Caption = Worksheets("Button Data Sheet").Range("A1").Offset(i, 0).Value
End With
i = i + 1
Loop Until Worksheets("Button Data Sheet").Range("A1").Offset(i, 0).Value = ""
End Sub
Private Sub Unknown_Click()
ActiveCell.Value = Me.Unknown.Caption
End Sub
Thank you very much!
EDIT followup question. Thank you chris nielsen for the even class module. But now I have trouble trying to refer which command button did I press as I need the button's caption to put on the active cell. I cannot use Userform1. because the command button is not generated yet.
Here is the code for the userform.
Option Explicit
Dim GenreArray() As New Class1
Dim Genre(0 To 20) As MSForms.CommandButton
Private Sub UserForm_Initialize()
Dim i As Integer
i = 0
Do
Set Genre(i) = Me.Controls.Add("Forms.CommandButton.1")
With Genre(i)
.Width = Me.Controls("Unknown").Width
.Height = Me.Controls("Unknown").Height
.Left = Me.Controls("Unknown").Left
.Top = Me.Controls("Unknown").Top + Me.Controls("Unknown").Height * (i + 1)
.Caption = Worksheets("Button Data Sheet").Range("A1").Offset(i, 0).Value
End With
ReDim Preserve GenreArray(0 To i)
Set GenreArray(i).clickEvent = Genre(i)
i = i + 1
Loop Until Worksheets("Button Data Sheet").Range("A1").Offset(i, 0).Value = ""
End Sub
Private Sub Unknown_Click()
ActiveCell.Value = Me.Unknown.Caption
End Sub
Here is the code for the class module.
Option Explicit
Public WithEvents clickEvent As MSForms.CommandButton
Private Sub clickEvent_click()
ActiveCell.Value = UserForm1.Unknown.Caption
End Sub