在vba中检索字典的集合类型元素

时间:2015-03-19 14:06:57

标签: excel vba excel-vba

我在vba中有一个字典,其中每个键都是一个字符串,每个值关联是一个集合,这是我的代码:

Dim dict As Dictionary
Set dict = New Dictionary

Set collec=New collection

Dim i As Integer
For i=1 To 5
    collec.Add "element" & i
Next i

dict.Add "mykey",collect

这是我被阻止的地方,我想通过这样的密钥来利用这个集合:

Dim test As New collection
test=dict("mykey")

但这不起作用

提前感谢您的帮助

2 个答案:

答案 0 :(得分:4)

分配对象时需要使用Set关键字。您的代码中也存在一些拼写错误(collec vs collect)。您应该使用Option Explicit来捕获这些类型的错误:

Option Explicit

Dim dict As Dictionary
Set dict = New Dictionary

Set collec = New collection

Dim i As Integer
For i=1 To 5
    collec.Add "element" & i
Next i

dict.Add "mykey", collec  'fix typo

Dim test As Collection
Set test = dict("mykey")   'use Set to assign object

答案 1 :(得分:-1)

Sub M_snb()
 With CreateObject("scripting.dictionary")
  For j = 1 To 5
   Set .Item("c_" & .Count) = New Collection
  Next

  .Item("c_2").Add "first"
  .Item("c_2").Add "second"
  .Item("c_2").Add "third"

  MsgBox .Item("c_2").Item(2)
 End With
End Sub