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

时间:2015-03-12 09:25:07

标签: excel vba variables excel-2007

我需要将变量的值称为另一个变量。 E.g。

我指定了FirstVariable = "One"

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

SecondVaribale = "FirstVariable"(请注意,这是" TEXT")

现在我可以调用或指定SecondVariable以任何方式将值返回为One吗?

表示这应该返回One

 Range("A1").Value = SecondVariable 

可能吗?

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

简单的方法是手动分配变量,将来需要手动干预我想避免。

1 个答案:

答案 0 :(得分:1)

您可以在VBA for Excel 2007中创建自己的自定义词典或集合。然后您可以“命名”您的变量,并使用另一个字符串变量来间接访问这些“命名变量”。使用Dictionary或Collection的选择是你需要它来改变“命名变量”的值。

字典允许您添加,读取,更改,以及删除键/值对。集合只允许添加,读取和删除;您必须使用子例程来更改键/值对。 Collection允许您使用数字索引(如数组)来访问键/值对;字典没有类似数组的功能。一个非常彻底的比较是http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/A_3391-Using-the-Dictionary-Class-in-VBA.html

因此,为了适应您的示例,并且还显示“命名变量”值的更改,以下是一些示例代码:

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