按键引用集合集合中的对象

时间:2014-03-19 06:29:42

标签: vba

首先,道歉,这是我的第一篇文章,因此我可能没有使用过最佳实践。

我正在使用VBA for Excel编写应用程序。

我创建了一个Class,然后将该类的几个对象实例化并将它们添加到Collection中。然后我将该Collection添加到另一个Collection中,并重复该过程,以便最终得到同一个Class的对象集合,就像我想的层次结构一样。

每当我添加到Collection时,我都会创建一个键来唯一标识我要添加的内容。我现在想要使用该键来引用“层次结构”中的特定对象。

以下伪有希望解释实例化对象的过程,添加到新的Collection,然后将Collection添加到新的Collection(为简单起见,我只添加了一个对象,从而产生了单个分支层次结构,而我的实际代码将多个对象添加到多个集合中。

Public Element As CElement
Public InsideCollection As Collection
Public OutsideCollection As Collection

Sub Main()

    Set Element = New CElement
    Set InsideCollection = New Collection
    Set OutsideCollection = New Collection

    Element.Field1 = "blah1"
    Element.Field2 = "blah2"

    InsideCollection.Add Element, Element.Field1

    OutsideCollection.Add InsideCollection, "ABCD"

End Sub

现在我已经将这些数据加载到一种层次结构中,如何在最低级别访问特定元素而不循环搜索正确的所有元素?我以为我可以按照以下方式做点什么:

OutsideCollection("ABCD").InsideCollection("blah1").Field2

OutsideCollection.InsideCollection("blah1").Field2  

但他们给出了这个错误:

  

运行时错误'438':对象不支持此属性或方法

我也尝试了上面的内容,用整数值引用元素,例如。

OutsideCollection(1).InsideCollection(1).Field2

但得到同样的错误。

有什么想法吗?

干杯,克里斯

2 个答案:

答案 0 :(得分:2)

很长的路。让我们定义另外两个变量innerColinnerEl

Dim innerCol As Collection
Dim innerEl As CElement

然后按键获取OutsideCollection集合的值:

Set innerCol = OutsideCollection("ABCD")

现在innerCol包含CElements的集合。让我们按键获得单个元素:

Set innerEl = innerCol("blah1")

变量innerEl包含CElement类型的对象,我们可以获取其属性:

MsgBox innerEl.Field1 ' returns "blah1"
MsgBox innerEl.Field2 ' returns "blah2"

简短,没有其他变量,我们可以使用这个:

MsgBox OutsideCollection("ABCD")("blah1").Field1 ' returns "blah1"
MsgBox OutsideCollection("ABCD")("blah1").Field2 ' returns "blah2"

答案 1 :(得分:0)

要通过文字访问对象,有"!"操作者:

Sub test_collection_intf()
  Dim v_a As New Collection
  v_a.Add Item:=New Collection, Key:="first"
  v_a!first.Add Item:=CreateObject("Scripting.Dictionary"), Key:="red"
  v_a!first!red!Type = "color"

  v_a.Add Item:=New Collection, Key:="second"
  v_a!Second.Add Item:=CreateObject("Scripting.Dictionary"), Key:="green"
  v_a!Second!green!scheme = "RGBA"

  Debug.Print "Access by literals"
  Debug.Print "v_a!first!red.Count:"; v_a!first!red.Count; "v_a!first!red!type: "; v_a!first!red!Type
  Debug.Print "v_a!Second!green.Count"; v_a!Second!green.Count; "v_a!Second!green!RGBA: "; v_a!first!red!RGBA
  Debug.Print "v_a!Second!green!scheme: "; v_a!Second!green!scheme
' But it is impossiable to use a variable to acces field of object as in Perl
'  Dim v_key_l1 As String, v_key_l2 As String
'  v_key_l1 = "first": v_key_l2 = "red"
'  Debug.Print "v_a!v_key_l1!v_key_l2:"; v_a; !v_key_l1; !v_key_l2
'  v_key_l1 = "second": v_key_l2 = "green"
'  Debug.Print "v_a!v_key_l1!v_key_l2:"; v_a!v_key_l1!v_key_l2
End Sub

立即窗口中的输出:

Access by literals
v_a!first!red.Count: 1 v_a!first!red!type: color
v_a!Second!green.Count 1 v_a!Second!green!RGBA: 
v_a!Second!green!scheme: RGBA
相关问题