VBA通过串联字符串和变量来创建变量名?
我目前正在编写一些VBA脚本,其最终目的是比较两个字典.
I am currently writing some VBA script with the final aim of comparing two dictionaries.
我有一个很大的循环,将信息从xml文件加载到字典中.简而言之,它的结局是这样的.
I have a large loop loading information into a dictionary from an xml file. To cut a long story short it ends with something like.
Dictionary.Add index, info
现在,我想添加具有2个字典(dictionary_1和dictionary_2)的功能,并通过将其合并到某种循环中来选择将信息写入哪个词典.这就是我的想法
Now i would like to add the functionality to have 2 dictionaries (dictionary_1 and dictionary_2) and choose which dictionary to write the information to by incorporating it in some kind of loop. This is what im thinking
for i=1 to 2
("dictionary_" & i).add key, info
next i
如果这行得通,显然会在两个字典中放入相同的信息,但这不是重点,我的问题是:
If this worked it would obviously just put the same information in the two dictionaries but that's not the point here, my question is:
我如何以这种方式引用变量以连接某种字符串和变量?
How do i reference a variable this way concatenating some kind of string and variable?
出于我以外的任何原因,是否有任何想法还是不可能/不是一个好主意?
Any thoughts or is this not possible/not a good idea for some reason that is beyond me?
您不能像这样快速地构造变量,但是可以创建字典数组:
You can't construct variables on the fly like that, but you can create an array of dictionaries:
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
您还可以执行诸如创建词典字典之类的操作,但是在您的情况下,一系列词典看起来很自然.
You can also do things like create a dictionary of dictionaries, but in your case an array of dictionaries seems natural.
请注意,如果您要沿着这条路线前进,则可以省去单个词典,而只需使用数组即可,如下所示:
Note that if you are going this route, you can dispense with the individual dictionaries and just use the array, like this:
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