【发布时间】:2017-06-16 03:39:22
【问题描述】:
我动态地创建一个带有组合框和文本框的用户表单。每行一个。用户将选择他想要的行数。 到目前为止,我可以根据行数调整 Userform 的大小并创建第一行。但是第二行出现错误: 运行时错误“-2147221005(800401f3)”:无效的类字符串 结果是Userform generated 这是我的代码。为了简化我将行变量分配给 Nb=3
Public Sub CommandButton2_Click()
Dim Nb As Integer 'Nb = number of people to record
Dim UF2 As Object
Dim TbHour, TbBin As msforms.TextBox 'txtbox for number of hours done and bins
Dim CBName As msforms.ComboBox 'List with names
Dim i 'i = loop to create rows
Nb = 3
Set UF2 = ThisWorkbook.VBProject.VBComponents.Add(3)
With UF2
.Properties("Caption") = "Packing record"
.Properties("Width") = "250"
.Properties("Height") = "50"
.Properties("Height") = .Properties("Height") * Nb + 10
End With
For i = 1 To Nb
Set CBName = UF2.Designer.Controls.Add("forms.combobox." & i) **'here is where the error happens on the second For/Next loop**
With CBName
.Name = "Combobox" & i
.Top = 0
.Top = .Top * i + 10
.Left = 10
.Width = 100
.Height = 20
End With
With UF2.CodeModule
.InsertLines 1, "Public sub userform_initialize()"
.InsertLines 2, "Me.ComboBox1.AddItem (""1"")"
.InsertLines 3, "End sub"
End With
Set TbHour = UF2.Designer.Controls.Add("forms.textbox." & i)
With TbHour
.Top = 0
.Top = .Top * i + 10
.Left = 120
.Width = 50
.Height = 20
End With
Next i
i = i + 1
Set TbBin = UF2.Designer.Controls.Add("forms.textbox." & i)
With TbBin
.Top = 10
.Top = .Top * i
.Left = 180
.Width = 50
.Height = 20
End With
VBA.UserForms.Add(UF2.Name).Show
ThisWorkbook.VBProject.VBComponents.Remove UF2
End Sub
【问题讨论】:
-
为什么不只声明一个
New ComboBox变量和.Add那个对象? -
这个怎么写?到目前为止,我一直使用 'controls.add("forms.xxxx.1")'
-
简体字适合评论...
Me.Controls.Add(New ComboBox)
标签: excel vba dynamic combobox