I need to create variables on the fly in Excel VBA, as for example users type Name and Age inside variable NAME and AGE. Suppose user type PETER in NAME and 34 in AGE, I want VBA to create a variable PETER with contents 34. This can be done easily in PHP.
I was able to make part of it works:
Person = Cells(10, 1).Value 'suppose it is "PETER"
Age = Cells(11, 1).Value 'suppose it is "34"
Creating the Variable
Names.Add Name:=Person, RefersTo:=Age
Retrieving it
Debug.Print Person ' prints PETER
Debug.Print Evaluate(Person) ' prints 34
Debug.Print PETER ' Variable PETER does not exist
The above doesn't help me, since it is the same as creating a Variable "NAME" with contents PETER, when evaluated shows 34. I need Variable PETER with contents 34.
The problem is;
PERSON="PETER"
AGE="34"
Name.Add Name:=PERSON RefersTo:=Age
creates a variable PERSON=34, not PETER=34.
Name.Add Name:=Evaluate(Person)
... does not work.
Any help please?
Update from 03/22/2019 1:38pm
Following some tips and discoveries, Dictionary is what solve my problem.
Sub T1()
Dim MAGIC As New Scripting.Dictionary
AnyVar = "R10" 'sets [AnyVar] = "R10"
Magic(AnyVar) = 25 'sets [R10] = "25"
Magic("ARTEN") = "R10" '[ARTEN] points to R10
Magic("R10") = 33 'sets [R10] = "33"
N5 = Magic("ARTEN") 'sets N5 = "R10"
N6 = Magic(N5) 'sets N6 = [R10] (33)
Debug.Print N5 & " = " & N6
End Sub
It printed "R10 = 33", exactly what I was willing to have. So now, with dictionary I can create variables on fly and find or change their values at easy.
To create a new entry on Magic (dictionary):
Magic.Add key:="name", Item:=33
If a text between quotes, the new entry will be that text. If without quotes, it assumes it is a variable containing the name/value.
V25 = "foo"
V26 = 33
Magic.Add key:=V25, Item:=V26
Will create an entry name "foo" with contents 33.
To change any existent entry, just
V25 = "foo"
V26 = 33
V29 = "fee"
V30 = "faa"
Magic(V25) = V26 '[foo] = 33
Magic("foo") = 38 '[foo] = 38
Magic(V29) = 39 '[fee] = 39
Magic(V25) = Magic(V29) + 1 '[foo] = [fee]+1 = 40
dictionary(V30) = V25 '[faa] = [V25] = "foo"
debug.print Magic(V30) 'prints "foo"
debug.print Magic(Magic(V30)) 'prints 40
V40 = "Paul"
V41 = "Smith"
Magic(V40) = V41
debug.print Magic("Paul") 'print Smith
If entry name "foo" exists, it will change the contents to the contents of V26, if the entry does not exist, it creates it.
So, you don't need to use the formal way to create an entry.
Magic.Add key:=V25, Item:=V26