How to create controls dynamically at runtime

后端 未结 2 1981
小蘑菇
小蘑菇 2021-01-27 04:41

I am trying to create a variable number of controls (combo boxes) in an excel userform based on the number of columns that are on a particular worksheet being viewed. Ideally I

2条回答
  •  轮回少年
    2021-01-27 04:46

    I can share with you an example of a Procedure I used to create some ComboBoxes at Run time.

    Private Sub Agrega_Combo(Unidades As Integer)
    'Procedimiento para agregar los ComboBox, etiquetas y unidades a la lista.
        Dim i, j As Integer
        Dim Cmb As Control
        Dim Lbl As Control
    
        'Ciclo para crear los ComboBox y Etiquetas en el 'ArrUnidades'
        For i = 1 To UBound(ArrUnidades)
        'Agrega el ComboBox
            Set Cmb = Me.Controls.Add("Forms.combobox.1")
            'Se establece el nombre y la posición del nuevo ComboBox
            With Cmb
                .Name = "Combobox" & i
                .Left = 66
                .Width = 36
                If i = 1 Then
                    .Top = 34
                Else
                    .Top = 34 + (24 * (i - 1))
                End If
            End With
        'Agrega la Etiqueta'
            Set Lbl = Me.Controls.Add("Forms.label.1")
            With Lbl
                .Name = "Label" & i
                .Caption = ArrUnidades(i) & " :"
                .Left = 30
                .Width = 36
                If i = 1 Then
                    .Top = 38
                Else
                    .Top = 38 + (24 * (i - 1))
                End If
            End With
            'Ciclo para agregar las unidades indicadas al llamar el procedimiento.
            For j = 1 To Unidades
                Me.Controls("ComboBox" & i).AddItem j
            Next j
            'Selecciona el primer valor de la lista.
            Me.Controls("ComboBox" & i).Text = Me.Controls("ComboBox" & i).List(0)
        Next i
    End Sub
    

    Hope it helps.

提交回复
热议问题