如何将用户窗体上的控件对象添加到集合中,然后遍历集合并访问它们的属性?
How do I add control objects on a userform to a collection, and then loop through the collection and access their properties?
我在用户窗体中有以下代码。我试图将表单上组合框的某个子集添加到一个集合中,然后循环遍历该集合。它似乎是将组合框的值添加到集合而不是控制对象本身......?添加到集合后,我需要使用什么标识符或 属性 才能访问组合框对象的 .Text
属性?
'Put comboboxes in a collection
Dim oColl As Collection
Set oColl = New Collection
Dim cb As Control
For Each cb In Me.Controls
If TypeName(cb) = "ComboBox" Then
' I suspect it may be this line going wrong:
If IsNumeric(cb.Text) Then oColl.Add (cb)
End If
Next
' Trying to loop through the collection of comboboxes
' I've tried to declare ctrl as MSForms.ComboBox, ComboBox, Control, Object,
' and Variant, results are the same...
Dim ctrl As MSForms.ComboBox
Dim i As Integer
For i = 1 To oColl.count
For Each ctrl In oColl
' This line produces an object required error on ctrl
If CInt(ctrl.Text) = line Then
你太接近了。这只是一些语法错误,即 collection.add 后面有括号。
示例:遍历用户窗体上的所有组合框,将其中包含数字的组合框存储在集合中。循环遍历集合并显示每个 combobox.text 的消息。在 CommandButton1 单击事件时触发。代码进入用户表单本身,因为我们引用 me.controls
Private Sub CommandButton1_Click()
Dim oColl As Collection
Set oColl = New Collection
Dim cb As Control
For Each cb In Me.Controls
If TypeName(cb) = "ComboBox" Then
If IsNumeric(cb.Text) Then oColl.Add cb 'Indeed here you had unneeded brackets. Alternative would be "Call oColl.Add(cb)"
End If
Next cb
For Each cb In oColl
MsgBox cb.Text
Next cb
End Sub
编辑:您可以只声明一个变量 ComboBox,但是当您遍历所有控件 (For Each Control in Me.Controls
) 时,您将遇到类型不匹配错误。
我在用户窗体中有以下代码。我试图将表单上组合框的某个子集添加到一个集合中,然后循环遍历该集合。它似乎是将组合框的值添加到集合而不是控制对象本身......?添加到集合后,我需要使用什么标识符或 属性 才能访问组合框对象的 .Text
属性?
'Put comboboxes in a collection
Dim oColl As Collection
Set oColl = New Collection
Dim cb As Control
For Each cb In Me.Controls
If TypeName(cb) = "ComboBox" Then
' I suspect it may be this line going wrong:
If IsNumeric(cb.Text) Then oColl.Add (cb)
End If
Next
' Trying to loop through the collection of comboboxes
' I've tried to declare ctrl as MSForms.ComboBox, ComboBox, Control, Object,
' and Variant, results are the same...
Dim ctrl As MSForms.ComboBox
Dim i As Integer
For i = 1 To oColl.count
For Each ctrl In oColl
' This line produces an object required error on ctrl
If CInt(ctrl.Text) = line Then
你太接近了。这只是一些语法错误,即 collection.add 后面有括号。
示例:遍历用户窗体上的所有组合框,将其中包含数字的组合框存储在集合中。循环遍历集合并显示每个 combobox.text 的消息。在 CommandButton1 单击事件时触发。代码进入用户表单本身,因为我们引用 me.controls
Private Sub CommandButton1_Click()
Dim oColl As Collection
Set oColl = New Collection
Dim cb As Control
For Each cb In Me.Controls
If TypeName(cb) = "ComboBox" Then
If IsNumeric(cb.Text) Then oColl.Add cb 'Indeed here you had unneeded brackets. Alternative would be "Call oColl.Add(cb)"
End If
Next cb
For Each cb In oColl
MsgBox cb.Text
Next cb
End Sub
编辑:您可以只声明一个变量 ComboBox,但是当您遍历所有控件 (For Each Control in Me.Controls
) 时,您将遇到类型不匹配错误。