Create event handlers for multiple dynamic controls

前端 未结 2 995
孤街浪徒
孤街浪徒 2020-12-04 01:28

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

相关标签:
2条回答
  • 2020-12-04 01:42

    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
    
    0 讨论(0)
  • 2020-12-04 01:58

    @user3538102 .. To your comment regarding Textbox's. Below is example is an example. I added Combo box select either CommandButton or TextBox and generate events. The code works but could be better.

    I added combo box to select to dynamically generate object type.

    Combo Box

    In UserForm Activate event - Add combo drop down list

    Private Sub UserForm_Activate()
        ComboBox1.AddItem "CommandButton"
        ComboBox1.AddItem "TextBox"
        ComboBox1.ListIndex = 0
    End Sub
    

    In Class1 Class Module ..

    ClassModule

    Modified UserForm code ..

    Option Explicit
    
    Dim cObjs() As New Class1
    
    Private Sub TextBox1_Change()
    Dim i As Integer
    Dim buttonStartPosition As Integer
    Dim cObj As Object
    
    buttonStartPosition = 30
    
    If TextBox1 <> vbNullString Then
     For i = 1 To TextBox1.Value
        If ComboBox1.Value = "CommandButton" Then
            Set cObj = Me.Controls.Add("Forms.CommandButton.1")
        Else
            Set cObj = Me.Controls.Add("Forms.TextBox.1")
        End If
    
            With cObj
                .Name = ComboBox1.Value & i
                .Left = 15
                .Top = buttonStartPosition
                .Width = 30
                .Height = 14
            End With
    
        ReDim Preserve cObjs(1 To i)
        If ComboBox1.Value = "CommandButton" Then
            Set cObjs(i).ButtonGroup = cObj
        Else
            Set cObjs(i).TextGroup = cObj
        End If
    
        buttonStartPosition = buttonStartPosition + 14
    
     Next i
    End If
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题