循环 VBA class 制作的集合

Loop a collection made by VBA class

我正在尝试循环播放一个集合。我可以展开并查看 VBE 中的“元素”,但出现错误:

"Object doesn't support this property or method".

我有一个标准模块

Public collItems As Collection

该集合在初始化时填充在用户窗体模块中

collItems.add cItems

cItems 是由 New clsItems 制成的对象,它是 class 模块。

class 模块由许多像这样的用户窗体控件组成:

Private WithEvents frm As msforms.Frame
Private WithEvents lbl As msforms.Label
Private WithEvents cmd As msforms.CommandButton
Private WithEvents txt1 As msforms.TextBox
Private WithEvents txt2 As msforms.TextBox 
+++

不确定 Private 是否适合继续此操作。

当用户窗体完成加载时,会出现动态数量的框架,每个框架内都包含所有这些文本框。它看起来像一个由 MS Project 中的数据制成的电子表格。命令按钮的工作是更改很多文本框的 attributes/properties.

我想循环 collItems 集合,但随后出现错误。

我的 class 中没有任何 getlet,只有一个 set 属性。 在 class 内添加 10 个独特的文本框可能看起来很愚蠢,但到目前为止我就是这样做的。所有表单对象都被赋予了在创建过程中引用行和列的名称,并帮助我识别它们。

失败的代码如下所示:

Sub changeBox(ByRef name As String)
For Each item in collItems.item(CLng(Replace(name, "cmd", "")))
    'blabla
Next item
End Sub

此测试有效并显示了我要循环的所有元素:

Set test = collItems.item(3) 'Meaning row 3 in userform

如何循环我的特定文本框并更改它们的属性?

So now I want to loop the collItems collection and write my code. But then I get an error...

该集合包含一系列 cItems 类型的对象。因此,要循环集合项,请声明一个此类对象用作迭代器。

请注意,class 成员必须 public 公开才能在 cItems class 之外访问。不确定如何实例化它们,但可以通过 public read-only 属性.

公开它们
Public Property Get Form() As msforms.Frame
    Set Form = frm
End property

循环:

Dim objCurrent As cItems, frm As msforms.Frame  

For Each objCurrent in collItems
     'here you can use the objCurrent to access the current item.
    Set frm = objCurrent.Form
    '...
Next objCurrent

为了能够通过名称获取控件,请在 cItems class 中创建一个字典来存储控件并使用键检索对象。

看下面的例子:

'dictionary
Private m_boxes As Object

Public Sub AddTextBox(ByVal Key As String, ByVal obj As msforms.TextBox)
    m_boxes.Add Key, obj
End Sub

Public Function GetTextBox(ByVal Key As String) As msforms.TextBox
    Set GetTextBox = m_boxes(Key)
End Function

Private Sub Class_Initialize()
    Set m_boxes = CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate()
    Set m_boxes = Nothing
End Sub

如何称呼它:

Dim txt As msforms.TextBox
Set txt = objCurrent.GetTextBox("txt1")