1

How do I populate a series of variables that use a common prefix followed by a number using a For loop so I don't have without writing them individually?

I have seen it done before but I can't find that example to replicate. It was something along the lines of this...

For i = 0 to 9
    var("Home" & i) = "Yes"
Next i

TIA

1
  • 2
    No, this is not possible. Use arrays in such scenarios. Commented Jul 1, 2019 at 13:02

3 Answers 3

3

Anytime you think "Variable variable names" think instead "Array".

Dim HomeArray(0 to 9) As String

For i = 0 to 9
    HomeArray(i) = "Yes"
Next i
Sign up to request clarification or add additional context in comments.

Comments

2

It is possible, but only if your variables are PUBLIC and in a CLASS:

' Class1

Public Home0 As String
Public Home1 As String
Public Home2 As String
Public Home3 As String
Public Home4 As String
Public Home5 As String
Public Home6 As String
Public Home7 As String
Public Home8 As String
Public Home9 As String

Then you can use CallByName() like this:

' Module1

Dim C1 As New Class1

Sub Foo_In_Module1()
    Debug.Print "Before: Home0 = " & C1.Home0
    For i = 0 To 9
        CallByName C1, "Home" & i, VbLet, "Yes"
    Next i
    Debug.Print "After: Home0 = " & C1.Home0
End Sub

Output in my Immediate window:

enter image description here

An example of retrieving those same values with CallByName():

Sub Foo2_In_Module1()
    Dim varName As String
    For i = 0 To 9
        varName = "Home" & i
        Debug.Print varName & " = " & CallByName(C1, varName, VbGet)
    Next i
End Sub

Comments

1

Maybe what you are looking for is a dictionary:

dict.Add Key:="Orange", Item:=45

if you want to set the value of "orange" you can use like this:

dict("Orange") = 75

take a look Here

Comments

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.