如何调用名称作为文本传递给另一个变量的变量的值?

How to call a value of a variable whose name is passed as text to another variable?

我需要调用一个变量的值作为另一个变量。例如

我分配给FirstVariable = "One"

然后我将名称作为文本分配给

SecondVaribale = "FirstVariable"(注意这里是"TEXT")

那么现在我可以通过任何方式将 SecondVariable 调用或分配给 return 作为 One 的值吗?

意味着这应该 return One:

 Range("A1").Value = SecondVariable 

这可能吗?

因为我有大约 40 个这样的变量要在大约 4 - 6 个实例中完成,我想通过 Excel 中的映射 sheet。

最简单的解决方法是手动分配变量,这将需要我希望避免的手动干预。

您可以在 VBA 中为 Excel 2007 创建您自己的自定义字典或集合。然后您可以 "name" 您的变量,并使用另一个字符串变量间接访问那些 "named variables"。使用 Dictionary 或 Collection 的选择是您需要它来更改 "named variable".

的值有多容易

词典允许您添加、阅读、更改 和删除key/value 对。 Collection 只允许添加、读取和删除;您必须使用子程序来更改 key/value 对。 Collection 允许您使用数字索引(如数组)来访问 key/value 对;字典没有类似数组的特性。 http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/A_3391-Using-the-Dictionary-Class-in-VBA.html

有一个非常彻底的比较

因此,为了调整您的示例,并显示 a "named variable" 值的变化,这里有一些示例代码:

Public Function test() As String
    ' Dictionary example
    Dim myDictionary, SecondVariable As String
    Set myDictionary = CreateObject("scripting.dictionary")
    myDictionary.Add "FirstVariable", "Four"
    myDictionary.Add "AnotherVariable", "Two"

    SecondVariable = "FirstVariable"

    ' note that "FirstVariable" must be already defined in the Dictionary else an error will occur; from your example this seemed to be the case
    ' if this was not the case then will need a more complex line using: If myDictionary.exists(SecondVariable) Then ... Else ...
    myDictionary.Item(SecondVariable) = "One"
    test = myDictionary.Item(SecondVariable) 'function returns "One"; the current value of "FirstVariable" in the Dictionary
End Function

Public Function test2() As String
    ' Collection example
    Dim myCollection As New Collection, SecondVariable As String
    myCollection.Add "Four", "FirstVariable"
    myCollection.Add "Two", "AnotherVariable"

    SecondVariable = "FirstVariable"

    'myCollection(SecondVariable) = "One"     'Cannot do this with a Collection; have to use a Sub like the example below
    Call setCollectionValue(myCollection, SecondVariable, "One")
    test2 = myCollection(SecondVariable)  'function returns "One"; the current value of "FirstVariable" in the Collection
End Function

Private Sub setCollectionValue(collect As Collection, key As String, value As String)
    On Error Resume Next
    collect.Remove key
    On Error GoTo 0

    collect.Add value, key
End Sub