我已经创建了用户表单并在excel VBA中动态添加了控件。现在我想计算我添加的文本框的数量,并且还希望在用户输入文本框时捕获文本框值。请帮帮我。
public dynuserform as object
Sub answer()
Dim options As Variant
Dim txtbx As MSForms.TextBox
Dim cmdbtn As MSForms.CommandButton
Dim txtcap As Variant
Dim cntl As Control
Set dynuserform = ThisWorkbook.VBProject.VBComponents.Add(3)
With dynuserform
.Properties("Height") = 100
.Properties("Width") = 200
End With
with dynuserform
txtcap = "some array with dynamic size"
For i = LBound(txtcap) To UBound(txtcap)
Set txtbx = .designer.Controls.Add("forms.Textbox.1")
With txtbx
.Left = 180
If i = 0 Then
.Top = 30
Else
.Top = (30 * i) + 25
End If
.Height = 25
.Width = 90
End With
Next i
Set cmdbtn = .designer.Controls.Add("forms.CommandButton.1")
With cmdbtn
.Caption = "next"
.Height = 25
.Left = 190
.Top = 80
End With
end with
dynuserform.codemodule.insertlines 1, "Public ans As String"
dynuserform.codemodule.insertlines 2, "Private Sub CommandButton1_Click()"
dynuserform.codemodule.insertlines 3, " if txtboxcount>1 then"
dynuserform.codemodule.insertlines 4, " ans = ansload"
dynuserform.codemodule.insertlines 5, " 'Else"
dynuserform.codemodule.insertlines 6, " 'ans = TextBox1.Value"
dynuserform.codemodule.insertlines 7, " 'End If"
dynuserform.codemodule.insertlines 8, "End Sub"
VBA.UserForms.Add(dynuserform.Name).Show
end sub
一旦用户单击命令按钮,我想计算文本框的计数,我在fucntion中定义了它,但它显示了一个未设置的错误对象变量。 我想知道如何使用dynuserform对象来查找计数。请教我帮忙。
function txtboxcount() as long
Dim iCtrl As Long
countTextboxes = 0
For iCtrl = 0 To dynuserform.designer.Controls.Count - 1
If TypeName(dynuserform.designer.Controls(iCtrl)) = "TextBox" Then
countTextboxes = countTextboxes + 1
Debug.Print countTextboxes
End If
Next iCtrl
txtboxcount = countTextboxes
End Sub