2016-02-24 196 views
2

我目前正在寫一些VBA腳本比較兩個庫的最終目的。VBA通​​過連接字符串和變量創建一個變量名?

我有一個大的循環加載信息到從XML文件的字典。長話短說它以類似的東西結束。現在

Dictionary.Add index, info 

我想補充的功能有2個字典(dictionary_1和dictionary_2),並選擇通過將其在某種循環來寫一個字典中的信息。這是林想

for i=1 to 2 
    ("dictionary_" & i).add key, info 
next i 

如果這個工作這顯然只是把相同的信息在兩個庫,但這裏不是重點,我的問題是:

我如何引用變量這種方式連接某種字符串和變量?

任何想法,或者這是不可能的/不是出於某種原因,超出了我一個好主意?

回答

4

你不能建造在這樣的動態變量,但你可以創建詞典的數組:

Sub test() 
    Dim dictionary_1 As Object 
    Dim dictionary_2 As Object 
    Dim dictionaries As Variant 

    Set dictionary_1 = CreateObject("Scripting.Dictionary") 
    Set dictionary_2 = CreateObject("Scripting.Dictionary") 

    ReDim dictionaries(1 To 2) 
    Set dictionaries(1) = dictionary_1 
    Set dictionaries(2) = dictionary_2 

    dictionaries(1).Add "a", 1 
    dictionaries(2).Add "a", 2 

    Debug.Print dictionary_1("a") 'prints 1 
    Debug.Print dictionary_2("a") 'prints 2 
End Sub 

你也可以做這樣的事情創建詞典的詞典,但在你的情況下,一個數組的字典似乎很自然。

請注意,如果你走這條路,你可以用個人字典免除,只是使用數組,像這樣:

Sub test() 
    Dim dictionaries As Variant 

    ReDim dictionaries(1 To 2) 
    Set dictionaries(1) = CreateObject("Scripting.Dictionary") 
    Set dictionaries(2) = CreateObject("Scripting.Dictionary") 

    dictionaries(1).Add "a", 1 
    dictionaries(2).Add "a", 2 

    Debug.Print dictionaries(1)("a") 'prints 1 
    Debug.Print dictionaries(2)("a") 'prints 2 
End Sub 
+0

Ooo是的,這樣的事情可以工作。謝謝約翰。 –

0

我工作的一個類似的解決方案,以通過John Coleman提出的一個。

Sub dueling_dictionaries() 
    Dim dDICTs() As Object, vVALs As Variant, i As Long, j As Long 

    vVALs = Range("A1:B4").Value2 

    ReDim dDICTs(1 To 2) 
    Set dDICTs(1) = CreateObject("Scripting.Dictionary") 
    Set dDICTs(2) = CreateObject("Scripting.Dictionary") 

    dDICTs(1).comparemode = vbTextCompare 
    dDICTs(2).comparemode = vbTextCompare 

    For i = LBound(vVALs, 1) To UBound(vVALs, 1) 
     For j = LBound(vVALs, 2) To UBound(vVALs, 2) 
      dDICTs(j).Add Key:=vVALs(i, j), Item:=vVALs(i, 2 + CBool(j = 2)) 
     Next j 
    Next i 

    Erase vVALs 'going to reuse this in the following loops 

    For Each vVALs In dDICTs(1) 
     Debug.Print "key: " & vVALs & " - Item: " & dDICTs(1).Item(vVALs) 
    Next vVALs 

    For Each vVALs In dDICTs(2) 
     Debug.Print "key: " & vVALs & " - Item: " & dDICTs(2).Item(vVALs) 
    Next vVALs 

End Sub 

dueling_dictionaries

結果從即時窗口。

key: A - Item: 1 
key: B - Item: 2 
key: C - Item: 3 
key: D - Item: 4 
key: 1 - Item: A 
key: 2 - Item: B 
key: 3 - Item: C 
key: 4 - Item: D 
+0

謝謝,首先是最快手指的情況。我很高興看到每個人都同意 –

相關問題