Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Refering to Variable Names with a String 1

Status
Not open for further replies.

duGly

Technical User
Nov 13, 2006
52
US
Is there a way to refer to a variable by constructing a string to represent its name?

For example, say I have the following variables:
• myLevel
• intLevel1
• intLevel2
• intLevel3

My code now looks like this:
Code:
Select Case myLevel
    Case 1
        intLevel1 = intLevel1 + 1
    Case 2
        intLevel2 = intLevel2 + 1
    Case 3
        intLevel3 = intLevel3 + 1
End Select
I would really like it to look something like this (forgive the syntax–I know it doesn't work this way; hence the question):
Code:
VariableName("intLevel" & myLevel)=VariableName("intLevel" & myLevel) + 1
 
Use an array or a dictionary.

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
I'm familiar with arrays, but what do you mean by dictionary?
 
You would need to add a reference to the Scripting library then you could do something like (air code):

Set dicTest = CreateObject("Scripting.Dictionary")

dicTest.Add "One", 1
dicTest.Add "Two", 2
dicTest.Add "Three", 3

Debug.Print dicTest("One")

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Whenever you find yourself needing variable names like v1, v2,...vn, it almost always means your design is wrong (admittedly, VBA doesn't help here with its auto-generated naming scheme).

Here, for example, Level1 through 3 could be replaced by an array of Int with 3 members.
Code:
Levels(Level - 1) = Levels(Level - 1) + 1
then achieves the same effect as your Case statement (although an initial sanity check of the value of Level to make sure it is within the array bounds is probably a good idea). Suppose you had 150 levels? Or 1200? The Case statement would quickly become unworkable.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top