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

Excel 如何调用名称作为文本传递给另一个变量的变量的值?,excel,vba,variables,excel-2007,Excel,Vba,Variables,Excel 2007,我需要调用一个变量的值作为另一个变量。例如 我分配FirstVariable=“One” 然后我将名字作为文本签名到 SecondVaribale=“FirstVariable”(注意这里是“文本”) 那么现在我可以调用或分配第二个变量,以任何方式将值返回为One 意味着它应该返回一个: Range("A1").Value = SecondVariable 可能吗 因为我有大约40个这样的变量要在大约4-6个实例中完成,我想在Excel中通过一个映射表来驱动这些变量 简单的解决方法是手动分

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

我分配
FirstVariable=“One”

然后我将名字作为文本签名到

SecondVaribale=“FirstVariable”
(注意这里是“文本”)

那么现在我可以调用或分配第二个变量,以任何方式将值返回为
One

意味着它应该返回一个:

 Range("A1").Value = SecondVariable 
可能吗

因为我有大约40个这样的变量要在大约4-6个实例中完成,我想在Excel中通过一个映射表来驱动这些变量


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

您可以在VBA for Excel 2007中创建自己的自定义词典或集合。然后可以“命名”变量,并使用另一个字符串变量间接访问这些“命名变量”。使用字典或集合的选择取决于更改“命名变量”的值所需的简单程度

字典允许您添加、读取、更改和删除键/值对。集合只允许添加、读取和删除;必须使用子例程来更改键/值对。集合允许您使用数字索引(如数组)访问键/值对;字典没有类似数组的功能。一个相当彻底的比较正在进行中

因此,为了适应您的示例,并显示“命名变量”值的变化,下面是一些示例代码:

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

为了进一步解释,我正在寻找一个类似的值,比如FV=Userform1.TextBox1.value,然后分配SV=“TextBox1”,所以当我说Userform1.Controls(SV).value时,它的值计算为TextBox1的值。那么,我如何在没有用户表单的情况下使用相同的逻辑呢?我认为这是不可能的。让我们看看其他人怎么说。@pnuts不在这里,我将在运行时从分配的列表中调用它