开发者

How can I get reference to a variable by using a string, in VBA?

开发者 https://www.devze.com 2023-03-19 02:38 出处:网络
I have a variable strFunction, then I have another string strName = \"strFunction\" , what I want to know is how can I get the value of strFunction by using strName.

I have a variable strFunction, then I have another string strName = "strFunction" , what I want to know is how can I get the value of strFunction by using strName.

For example, something like getValue(strName) gives me the value of strFunction. Is it possible in Access VBA?

Thanks!

EDIT:

I have a strFunction string, it's a const string. In my code I want to use Len("strFunction") to test the length of it, but what i got is the length "strFunction".开发者_运维问答 So I need a get-value-out-of-variable-name function. I have tried Eval(), but it cannot do this, even I write a get_strFunction(), eval("get_strFunction()") gives me error, telling me it cannot find it.

Private Const strFunction as String = "FilterByType_1"
Private Function get_strFunction()
    get_strFunction = strFunction
End Function


"I have a variable strFunction, then I have another string strName = "strFunction" , what I want to know is how can I get the value of strFunction by using strName."

Instead of a variable, strFunction could be the key for an item in a VBA collection.

Public Sub darkjh()
    Dim strName As String
    Dim col As Collection
    Set col = New Collection
    col.Add "FilterByType_1", "strFunction"
    strName = "strFunction"
    Debug.Print col(strName)
    Set col = Nothing
End Sub

Edit: Instead of a VBA collection, you could use a Scripting.Dictionary.

Dim strName As String
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "strFunction", "FilterByType_1"
strName = "strFunction"
Debug.Print dict(strName)
Set dict = Nothing


Option Compare Database

Dim a As String
Dim b As String

Public Sub test()
    a = "b"
    b = "test-string"
    Debug.Print Eval("get" & a & "()")
End Sub

Public Function getB() As String
    getB = b
End Function

Output

>>test
test-string

eval(a) did not work, so I had to write a "getter" for the variable and eval that function: eval("get" & a & "()").

0

精彩评论

暂无评论...
验证码 换一张
取 消