Excel VBA字典重复键

时间:2014-10-13 11:25:42

标签: excel vba dictionary hashmap

我有这段代码:

Dim list As Object
Set list = jsonParse.Item("list")

Dim groupedByProjectElement As New Dictionary
For i = 1 To 2
        Set pE = list(i).Item("projectElement")
        Dim projectElementsDictionary As New Dictionary
        If groupedByProjectElement.Exists(pE.Item("businessKey")) Then
            Set projectElementsDictionary = groupedByProjectElement(pE.Item("businessKey"))
            projectElementsDictionary.Add projectElementsDictionary.count + 1, list(i)
        End If
        If Not groupedByProjectElement.Exists(pE.Item("businessKey")) Then
            projectElementsDictionary.Add 1, list(i)
            groupedByProjectElement.Add pE.Item("businessKey"), projectElementsDictionary
        End If
Next i

在第二次迭代中,我收到错误:

This key is already associated with an element of this collection

但我希望在第二次迭代中 projectElementsDictionary 应该是一个新词典。

我错过了什么?

列表看起来像这样:

"list": [
    {
        "projectElement": {
            "businessKey": "123",
            "customerUnit": {
                "businessKey": "123",
                "links": [],
                "shortDescription": "123",
                "text": "123",
                "version": null
            }
        }  
    }
]

1 个答案:

答案 0 :(得分:1)

我会回答我自己的问题:

Dim groupedByProjectElement As New Dictionary
For i = 1 To 25
    Set pE = List(i).Item("projectElement")
    Dim projectElementsDictionary As Dictionary
    If groupedByProjectElement.Exists(pE.Item("businessKey")) Then
        Set projectElementsDictionary = groupedByProjectElement(pE.Item("businessKey"))
        projectElementsDictionary.Add projectElementsDictionary.Count + 1, List(i)
    Else
        Set projectElementsDictionary = New Dictionary
        projectElementsDictionary.Add 1, List(i)
        groupedByProjectElement.Add pE.Item("businessKey"), projectElementsDictionary
    End If
Next i