riktek
Member
- Local time
- Today, 15:42
- Joined
- Dec 15, 2023
- Messages
- 135
I would like to programmatically construct a constant's name and return its value, but am stuck.
Eval() seems the most logical approach but it chokes, as follows.
At the top of a standard module, I do, e.g.:
Then, in the same module a public function attempts to return a constant's value with the call
I understand Eval() cannot read local variables, i.e., those declared in the calling procedure. The first two failures above seem to illustrate this for a local variable and a parameter. The third attempt is the most puzzling because the same error occurs with no local variable reference. Finally, Eval() takes the constant name directly and not as a string and errors similarly with the constant's value. In the latter case, I presume Eval() gets the constant's value and attempts to evaluate it.
To be clear, the question is how to get the constant's value from the string being passed, not necessarily about getting Eval() working although that would work if it's possible.
Any thoughts would be most appreciated.
Eval() seems the most logical approach but it chokes, as follows.
At the top of a standard module, I do, e.g.:
Code:
Public Const conFooBar As String = "conFooBarValue"
Then, in the same module a public function attempts to return a constant's value with the call
GetConstantValue("Foo")
and Eval() can't find the constant's name even though it is module-level and therefore in scope, and doubly so because it is declared Public. E.g.:
Code:
Function GetConstantValue(strStem As String) As Variant
Dim strConstantName As String
Dim strReturn As String
strConstantName = "con" & strStem & "Bar"
' strReturn = Eval(strConstantName) 'Throws 2482, can't find name 'conFooBar'.
' strReturn = Eval("con" & strStem & "Bar") 'Throws same.
' strReturn = Eval("conFooBar") 'Throws same.
' strReturn = Eval(conFooBar) 'Throws same, but for 'conFooBarValue'. Odd.
GetConstantValue = strReturn
End Function 'GetConstantValue()
I understand Eval() cannot read local variables, i.e., those declared in the calling procedure. The first two failures above seem to illustrate this for a local variable and a parameter. The third attempt is the most puzzling because the same error occurs with no local variable reference. Finally, Eval() takes the constant name directly and not as a string and errors similarly with the constant's value. In the latter case, I presume Eval() gets the constant's value and attempts to evaluate it.
To be clear, the question is how to get the constant's value from the string being passed, not necessarily about getting Eval() working although that would work if it's possible.
Any thoughts would be most appreciated.