首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何调用其名称作为文本传递给另一个变量的变量的值?

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

Stack Overflow用户
提问于 2015-03-12 09:25:07
回答 1查看 320关注 0票数 1

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

我分配FirstVariable = "One"

然后我把名字作为文本签给

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

因此,现在我可以调用或分配SecondVariable以任何方式将值作为One返回吗?

意味着这应该返回One

代码语言:javascript
复制
 Range("A1").Value = SecondVariable 

这有可能吗?

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-22 09:18:12

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

字典允许您添加、读取、更改和删除键/值对。集合只允许添加、读取和删除;您必须使用子例程来更改键/值对。集合允许您使用数字索引(如数组)访问键/值对;字典没有类似数组的特性。一个相当彻底的比较是在3391-Using-the-Dictionary-Class-in-VBA.html

因此,为了调整示例,并显示“命名变量”的值更改,下面是一些示例代码:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29005917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档