我试图遍历一个名为a1,a2等的变量列表...并动态构造变量的名称,如下所示:
a1 = 7
For RowNum = 1 to 10
MyVar = "a" & RowNum
'use MyVar in calculation
MsgBox MyVar
Next RowNum
问题是我需要MyVar的值,我得到的就是名字。这里,在循环的第一次迭代中,MsgBox显示" a1"我需要7.我使用.Value尝试了许多排列,我只是遇到了编译或运行时错误。
如何从文本名称中获取变量的值?这可以在VBA中完成吗?
提前致谢。
答案 0 :(得分:1)
您应该使用词典:
Sub Test()
Dim myVars As Object
Dim myVar As Variant
Dim RowNum As Long
Set myVars = CreateObject("Scripting.Dictionary")
myVars("a1") = 7
myVars("a5") = "xyz"
myVars("hello") = 42
For RowNum = 1 To 10
myVar = myVars("a" & RowNum)
'use MyVar in calculation
MsgBox "a" & RowNum & " contains " & myVar
If RowNum = 1 Then
MsgBox Range("D" & myVars("a" & RowNum)).Address
End If
Next RowNum
End Sub