VBA - 从字典中提取数组数据

时间:2016-10-04 14:59:10

标签: arrays excel vba dictionary

我已经填充了一个字典,其中包含链接到每个唯一键的多个数组。 E.g:

Dim dict As New Scripting.Dictionary
Dim x(5) As Variant
Dim prNumbers() as String
Dim prArrCount as Integer

prArrCount = 0

For i = 2 To lastRow
    'Populate relevant values (prNr, description etc. by reading them in.

    'Save the values in an array
    x(0) = prNr
    x(1) = description
    x(2) = priority
    x(3) = deliveryDate
    x(4) = delivery
    x(5) = endUser

    'Add to the dictionary if the key does not yet exist in it
    If Not dict.Exists(prNr) Then
        dict.Add prNr, x
        prNumbers(prArrCount) = prNr
        prArrCount = prArrCount + 1
    Else
        If priority < dict(prNr)(2) Then
            dict(prNr) = x
        End If
    End If

Next i

现在,我想打印整本字典的内容。我尝试将字典的内容加载到数组中,然后按如下方式打印数组。

For i = 3 To (prArrCount + 3)
    x = dict(prNumbers(i - 3))

    Range("A" & i).Value = i - 2
    Range("B" & i).Value = x(0)
    Range("C" & i).Value = x(1)
    Range("D" & i).Value = x(2)
    Range("E" & i).Value = x(3)
    Range("F" & i).Value = x(4)
Next i

问题在于它不允许我按照 x = dict(prNumbers(i-3))行将字典内容存储在数组中。有没有办法做到这一点,或另一种打印阵列的方式?

1 个答案:

答案 0 :(得分:0)

您不能将字典值分配给这样的数组。

这样的事情很好:

Sub TT()

    Dim dict As New Scripting.Dictionary
    Dim x(3) As Variant, y() As Variant

    x(0) = "A"
    x(1) = "B"
    x(2) = "C"
    x(3) = "D"

    dict.Add "blah", x

    y = dict("blah")

    Debug.Print Join(y, ",")

End Sub