我正在尝试根据正在查看的特定工作表上的列数在Excel Excel表单中创建可变数量的控件(组合框)。理想情况下,我想删除现有的并在运行时创建新的,而不是创建100左右,只是在可见和不可见之间来回切换。我目前所拥有的将创建一个组合框和循环,但它只创建1.它看起来好像组合框被覆盖并以最后创建的组合框结束。有什么建议可以在运行时将所有内容放到同一个用户窗体上吗?
Private Sub CommandButton1_Click()
Dim cCont As New Control
Dim ws As Worksheet
Dim lc As Long
Dim i As Long
Set ws = Loan_Data
lc = Loan_Data.Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To lc
Set cCont = Me.Controls.Add("Forms.CommandButton.1", "NewCombo" & i)
With cCont
.Caption = cCont.Name
.AutoSize = True
.Visible = True
End With
Next i
End Sub
答案 0 :(得分:2)
我可以与您分享我在运行时创建一些ComboBox的过程示例。
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
希望它有所帮助。
答案 1 :(得分:1)
通过一点点数学,你可以获得完全动态的。使用放置控件的框架。现在您有相对于框架的坐标。使用" y_offset"和" lineheight"变量和/或" x_offset"和"线宽"变量并创建具有计算位置(顶部和左侧)的控件。在创建过程中计算偏移量+(行*线高)并根据结果设置Frames ScrollHeight(和/或ScrollWidth)...
有时这样做。效果很好。