VBA通过连接字符串和变量来创建变量名?

时间:2016-02-24 12:40:51

标签: vba excel-vba excel

我目前正在编写一些VBA脚本,其最终目的是比较两个词典。

我有一个大循环从xml文件加载到字典中的信息。简而言之,它以类似的东西结束。

    Dictionary.Add index, info

现在我想添加2个字典(dictionary_1和dictionary_2)的功能,并通过将其合并到某种循环中来选择要写入信息的字典。这就是我的想法

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

如果这样做有效,显然只会在两个字典中输入相同的信息,但这不是重点,我的问题是:

如何通过连接某种字符串和变量来引用变量?

任何想法或者这不可能/不是因为某些原因超出我的好主意吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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