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

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

我将FirstVariable = "One"

然后我把名字分配给文本

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

那么现在我可以调用或分配SecondVariable以任何方式返回值为One

意思是这应该返回One

  Range("A1").Value = SecondVariable 

那可能吗?

因为我有大约40个这样的variables需要在Excel中的映射表中进行。

简单的方法是手动分配variables,这将需要以后手动干预,这是我想避免的。

您可以在VBA for Excel 2007中创build自己的自定义词典或集合。然后,您可以“命名”您的variables,并使用另一个stringvariables间接访问这些“命名variables”。 使用字典或集合的select是多么容易你需要它来改变一个“命名variables”的值。

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

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

 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