我正在使用 Excel VBA 创建库存管理工具。我创建了从 Internet Explorer 上的下拉框中收集名称列表并将它们放入数组中的代码。
我需要做的是类似vba create several textboxes comboboxes dynamically in userform的事情,但我会动态添加用户名标签和每个人将收到的 FLN 数量的文本框。然后,这些内容将进入我已经创建的预定义用户表单。
根据上面的代码示例,我意识到我无法使用 .Name = "Textbox"& i
重命名下一个标签或文本框。 i
必须等于一个不断变化的列表,因此它不能一成不变;因此为什么必须有与 UBound(UserArray)
一样多的标签和文本框。
已更新
Private Sub CreateControl()
Dim newTxt As msforms.Control, newLbl
Dim i As Integer, TopAmt
Dim UserArray As String
TopAmt = 30
For i = LBound(MyArray) + 1 To UBound(MyArray) - 1
Set newLbl = MultipleOptionForm.Controls.Add("Forms.Label.1")
With newLbl
.Name = "Label" & i
.Left = 10
.Top = TopAmt
.WordWrap = False
.AutoSize = True
.Visible = True
.Caption = MyArray(i)
Debug.Print .Name,
End With
Set newTxt = MultipleOptionForm.Controls.Add(bstrProgID:="Forms.Textbox.1", Name:="Textbox" & i)
With newTxt
.Left = 150
.Top = TopAmt
.Visible = True
.Width = 20
Debug.Print .Name
End With
TopAmt = TopAmt + newTxt.Height
Next
MultipleOptionForm.Show
End Sub
最佳答案
卢问题的答案具有误导性。该问题希望在添加控件时通过更改其 ProgID(bstrProgID 是引用要创建的类的字符串)来提供默认名称。
您可以重命名新控件,前提是其他控件不具有相同的名称。
您还可以将控件名称作为参数传递给 Controls.Add
方法。
您的标签未显示是因为您从未设置 Label.Caption
值。
Private Sub CreateControl()
Dim newLbl As MSForms.Label
Dim newTxt As MSForms.Control
Dim i As Integer, TopAmt
Dim UserArray As Variant
TopAmt = 50
UserArray = Array("Cat", "Dog", "Horse", "Gorrilla")
For i = LBound(UserArray) To UBound(UserArray)
Set newLbl = MultipleOptionForm.Controls.Add("Forms.Label.1")
With newLbl
.Name = "Label" & i
.Left = 50
.Top = TopAmt
.Visible = True
.Caption = UserArray(i)
Debug.Print .Name,
End With
Set newTxt = MultipleOptionForm.Controls.Add(bstrProgID:="Forms.Textbox.1", Name:="Textbox" & i)
With newTxt
.Left = 100
.Top = TopAmt
.Visible = True
Debug.Print .Name
End With
TopAmt = TopAmt + newTxt.Height
Next
End Sub
下一期:如何从这些动态创建的文本框中获取数据?
Dim newTxt As MSForms.Control
For i = LBound(UserArray) To UBound(UserArray)
set newTxt = MultipleOptionForm.Controls("Textbox" & i)
If UserArray(i) <> newTxt.Value then
'Do something
End if
Next
关于vba - 在运行时使用 vba 将多个标签和文本框添加到 Excel 用户窗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46078348/