Create event handlers for multiple dynamic controls

前端 未结 2 1003
孤街浪徒
孤街浪徒 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: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
    

提交回复
热议问题