Search code examples
vbaexcel

Create event handlers for multiple dynamic controls


I have a userform that creates two dynamic control buttons but I am having difficulty accessing the .name property of the dynamic control, which means I can't create the event handler correctly. Due to this problem I am unable to create event handlers. Below shows the code that creates the dynamic controls and also the code that I have written for the event handlers (which isn't functioning correctly)

Option Explicit

Public WithEvents cButton As MSForms.CommandButton


Private Sub TextBox1_Change()
  If TextBox1 <> vbNullString Then
     For i = 1 To TextBox1.Value        
        Set cButton = Me.Controls.Add("Forms.CommandButton.1")
        With cButton
            .Name = "CommandButton" & i
            .Left = 150
            .Top = buttonStartPosition
            .Width = 300
            .Height = 140
        End With
     Next i
   End If
End sub

 Private Sub cButton_Click()
    If cButton.Name = "CommandButton1" Then
      MsgBox "Button1"
    ElseIf cButton.Name = "CommandButton2" Then
      MsgBox "Button2"
    End If
 End Sub

Once this code is executed and the two buttons are on the screen, I press the first button (button1) and nothing happens but when I press the second button (button2) I receive the message "Button2". So how come I can't access the first button?


Solution

  • I got the events for multiple buttons to work with help from .. JWalk Excel Tips

    Below is the modification based on your code and the link provided.

    Create a Class module called Class1.

    Class1 Module

    Add modified code to UserForm1..

    Option Explicit
    
    Dim Buttons() As New Class1
    
    Private Sub TextBox1_Change()
        Dim i As Integer
        Dim buttonStartPosition As Integer
        Dim cButton As CommandButton
    
        buttonStartPosition = 30
    
        If TextBox1 <> vbNullString Then
            For i = 1 To TextBox1.Value
            Set cButton = Me.Controls.Add("Forms.CommandButton.1")
            With cButton
                .Name = "CommandButton" & i
                .Left = 15
                .Top = buttonStartPosition
                .Width = 30
                .Height = 14
            End With
            
            ReDim Preserve Buttons(1 To i)
            Set Buttons(i).ButtonGroup = cButton
            
            buttonStartPosition = buttonStartPosition + 14
            
            Next i
        End If
    
    End Sub