gpt4 book ai didi

vba - 如何在运行时动态创建控件

转载 作者:行者123 更新时间:2023-12-04 21:54:54 27 4
gpt4 key购买 nike

我正在尝试根据正在查看的特定工作表上的列数在 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

结束子

最佳答案

我可以与您分享一个我用来在运行时创建一些组合框的过程示例。

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

希望能帮助到你。

关于vba - 如何在运行时动态创建控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46980677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com