Get VBA variable value with variable name in string

Zari_the_girl

New Member
Joined
Nov 30, 2016
Messages
4
Dear VBA programmers,

I've searched all over the internet but have not yet found the solutions to the following issue:

I want to dynamically get the value of global variables by dynamically using the variable name.

So imagine there are global variables defined in a VBA Excel application (add-in) e.g.,

Public gsTestString as String
Public gsAnotherTest as String
etc etc.

that have values assigned to them at some point in some module, e.g.
gsTestString = "Hello"
gsAnotherTest = "Please help"

Now I want to make a function where one can enter the name of the global variable (as a string) and get the value of that variable back.

So for instance making a function GetVariableValue where GetVariableValue("gsTestString") would return "Hello", but GetVariableValue("gsAnotherTest") would return "Please help".

I don't want to put all variables and their values in arrays or anything similar, as the application has lots of different variables over different modules so putting all of those in arrays would be far from ideal.

Does anybody know how to refer to a variable if you only have its name in a String?

Thanks a lot in advance!
 
Mike

Could a class, in combination with CallByName, be used for what the OP wants to do?

AFAIK, CallByName is for procedures not variables.

I like your idea of Names.

Another option would be a VLOOKUP chart somewhere.

I'm wondering what info the OP's variables hold and how they are derived.
 
Upvote 0

Excel Facts

Control Word Wrap
Press Alt+Enter to move to a new row in a cell. Lets you control where the words wrap.

Forum statistics

Threads
1,223,268
Messages
6,171,100
Members
452,379
Latest member
IainTru

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top