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

时间:2016-02-04 01:29:00

标签: excel vba excel-vba combobox userform

我在UserForm中有以下代码。我试图将表单上的组合框的某个子集添加到集合中,然后循环遍历该集合。它似乎是将组合框的值添加到集合而不是控制对象本身......?添加到集合后,我需要使用什么标识符或属性才能访问组合框对象的.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

1 个答案:

答案 0 :(得分:1)

你真是太近了。这只是一些语法错误,即带有括号后面的collection.add。

示例:遍历userform上的所有组合框,将具有编号的组合存储在集合中。循环收集并显示每个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)时,您将收到类型不匹配错误。