Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vba

ms-access

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
like image 984
darkjh Avatar asked Oct 24 '22 06:10

darkjh


1 Answers

"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
like image 99
HansUp Avatar answered Oct 31 '22 09:10

HansUp