如何将用户窗体上的控件对象添加到集合,然后遍历集合并访问其属性?

我在UserForm中有以下代码。 我试图添加窗体上的combobox的某个子集到集合,然后遍历该集合。 它似乎是将combobox的值添加到集合而不是控件对象本身…? 添加到集合后,我需要使用什么标识符或属性才能访问combobox对象的.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,将其中的数字存储在集合中。 循环收集并显示每个combobox.text的消息。 触发CommandButton1点击事件。 代码进入用户me.controls本身,因为我们引用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 

编辑:你可以只声明一个variablescombobox,但是当你循环所有的控件( For Each Control in Me.Controls ),你会得到一个types不匹配的错误。