2016-10-04 44 views
0

我已經填充了一個字典,其中有多個數組鏈接到每個唯一鍵。例如:VBA - 從字典中提取數組數據

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 =字典(prNumbers(I - 3))。有沒有辦法做到這一點,或打印陣列的另一種方式?

+1

如果'x'是從代碼的第一位陣列然後'x'是一個數組。你必須指定數組的位置來存儲值 – Zac

+0

感謝你!我已經指定了什麼位置來保存字典中的各種項目,但現在我得到了類型不匹配?它來自字典(prNumbers(i - 3))(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