我正在尝试创建一个集合并放入
mydict = my_key:["a", "b", "c"]
然后迭代。
For Each V In mydict.keys
Debug.Print V
for z in mydict.Item(V)
Debug.Print z
next z
Next V
输出应该是这样的 我的钥匙 一个 b ç
但我有问题和错误,是否可以将一个集合存储在scripting.dictionary中?
或只是存储字符串" my_key":" a"," my_key2":" b"?
感谢。
答案 0 :(得分:2)
要将集合存储在字典中,您可以使用首先创建集合然后将其添加到字典的两步过程:
Sub test()
Dim C As Collection
Dim D As Object
Dim v As Variant
Set D = CreateObject("Scripting.Dictionary")
Set C = New Collection
C.Add "a"
C.Add "b"
C.Add "c"
D.Add "key1", C
Set C = New Collection 'Old collection safely stored in D
D.Add "key2", C 'Now D("key2") holds a collection
D("key2").Add "d"
D("key2").Add "e"
Debug.Print "Collection for key1:"
For Each v In D("key1")
Debug.Print v
Next v
Debug.Print "Collection for key2:"
For Each v In D("key2")
Debug.Print v
Next v
End Sub
该代码说明了如何添加回收集合变量C
以添加多个集合,以及如何将空集合添加到字典中以便稍后修改。
输出:
Collection for key1:
a
b
c
Collection for key2:
d
e
答案 1 :(得分:0)
在VBA中将集合放入字典是一个有趣的问题。当我们事先不知道键的数目和值时,它会更加有趣。假设这是我们在Excel中的输入:
在立即窗口 Ctrl + G 中,请求的输出如下所示:
这是将提供它的代码(运行Main
):
Public Sub Main()
Dim teamDictionary As New Dictionary
fillTeamDictionary teamDictionary
Dim myKey As Variant
Dim myVals As Variant
For Each myKey In teamDictionary
Debug.Print myKey; ":"
For Each myVals In teamDictionary(myKey)
Debug.Print vbTab; myVals
Next
Debug.Print "----------------"
Next
End Sub
Public Sub fillTeamDictionary(teamDictionary As Dictionary)
Dim myCell As Range
Dim teamRange As Range
With tblTeam
Set teamRange = .Range("A1:A8") 'range could be flexible...
End With
Dim myKey As String
Dim myVal As String
For Each myCell In teamRange
myKey = myCell
myVal = myCell.Offset(ColumnOffset:=1)
If teamDictionary.Exists(myKey) Then
teamDictionary(myKey).Add (myVal)
Else
Dim newList As Collection
Set newList = New Collection
newList.Add (myVal)
teamDictionary.Add myKey, newList
End If
Next myCell
End Sub
“技巧”是在每次需要时为字典的每个唯一键初始化一个新的Collection:
Dim newList As Collection
Set newList = New Collection
newList.Add (myVal)
teamDictionary.Add myKey, newList
然后,只要密钥存在,就将其添加到集合中:
If teamDictionary.Exists(myKey) Then
teamDictionary(myKey).Add (myVal)