2
votes

I've got code to build variables based on a string using Eval and Execute. But for whatever reason, Execute is leaving the variable empty when I try to set it to a variable. But works fine if I set it to a string manually

This DOES NOT work, Gives an empty box:

For j = 0 To 2
    name = "alias_" & j
    val = "test"
    Execute(Eval("name") + "=" + val)
    msgbox(Execute(Eval("name"))
Next

This DOES work, shows "test" in the msgbox:

For j = 0 To 2
    name = "alias_" & j
    Execute(Eval("name") + "=" + "test")
    msgbox(Execute(Eval("name"))
Next

So Execute doesn't seem to like the variable here. What's even stranger, in my VBSEdit debugger, I can see the locals, and it creates a local variable called "test" instead of setting the value to the alias_j variable. Totally confusing me now.

1
Don't construct variables like that. Ever. If you need indexed variables: use arrays. That's what they were invented for. - Ansgar Wiechers
Actually I would use dictionaries.. and will use dictionaries.. was having another vb-ism with dictionaries so I was trying something more creative with arrays, but didn't want iterative arrays. But I got dictionaries working properly now so this is defunct. Still good info... people are too afraid of 2 of the most powerful functions. - Dss
You're confusing "afraid" and "wary". - Ansgar Wiechers

1 Answers

2
votes

Are you trying to create variables named alias_0 thru alias_2 and assign a value to each? If so, this should work. It assigns the value test0 to alias_0, test1 to alias_1, etc.:

For j = 0 To 2
    name = "alias_" & j
    val = "test" & j
    Execute name & " = val"
    MsgBox Eval("alias_" & j)
Next