0

I have written a code that is able to generate a variable string that matches another variable name. But when I try to use that uppermost variable as cell value it pastes the variable name but not it's value.

So I have something like:

Public General as string
General = 10

and at some point I end up with a variable

dim CurrentValue as string 
CurrentValue = General

Where I mean to get that "10" but not "General" when I paste that CurrentValue as cell value, so I wonder if it's possible to do and if so then how could I do that?

11
  • 1
    Use a Scripting.Dictionary. Commented Sep 2, 2021 at 13:43
  • 1
    Use a dictionary. Add an item with a key of "General" and value of 10. Then you can look up "General" from the dictionary and return 10. Commented Sep 2, 2021 at 13:44
  • 1
    "General" (a String that looks like a variable) is not the same as General (a variable that is a String). Your current setup won't work. So use a dictionary with all your current public variables and their corresponding values. Commented Sep 2, 2021 at 13:49
  • 1
    learn.microsoft.com/en-us/office/vba/language/reference/… Commented Sep 2, 2021 at 13:51
  • 4
    A dictionary is a very old and very common object in most programming languages. Definitely something worth familiarizing yourself with. It's worth noting that anytime you think "Variable variables" or "Variable variable names" you are headed hard and fast towards a very bad time. The answer is almost always "Use an array", or in this case "Use a dictionary". Commented Sep 2, 2021 at 14:00

1 Answer 1

1

If you put your Global in the ThisWorkbook module (a worksheet module would also work) you could do something like this:

Option Explicit

Public General As Long

Function GetVar(varName As String)
    GetVar = CallByName(Me, varName, VbGet)
End Function

Then in a regular module:

Sub Tester()
    ThisWorkbook.General = 10
    Debug.Print ThisWorkbook.GetVar("General") ' >> 10
End Sub

In general though, a use case like this really signals a need to rethink things...

Sign up to request clarification or add additional context in comments.

2 Comments

FYI - do not take my example as an endorsement of what you're doing here... Referring to variables by their names as strings is generally a code smell....
That last sentence needs bolded, highlighted, underlined, italicized...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.