Loop with Changing Variable Names

Lloyd Christmas

New Member
Joined
Sep 17, 2009
Messages
2
I am trying to write a VBA macro without my Mr. Excel macro books available. I am going to make this simplistic as possible, hopefully it makes sense:

I have several variables (ex: Store1, Store2, Store3, Store4).

I have a process that does this (greatly simplified):

If Store1 = "Open" then ....
If Store2 = "Open" then....
If Store3 = "Open" then....
If Store4 = "Open" then...

I would like to just create a loop to clean it up (there are quite a bit more than 4, and I don't want to have hundreds of repeating lines of code)

For i = 1 to 4
If Store(i) = "Open" then.....
Next i

In this example, the first time through it would be Store1, the second time through it would be Store2, etc.

I can't quite get the syntax on the Store(i) part though. Store&i didn't work. Nor did "Store"&i

How do I refer to a variable name that is partially variable itself?
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
Hi,

Short answer, you can't.

What you (probably) need here is an array: one variable which holds all four values. You can then loop through the array.

Code:
Sub test()
    Dim Stores(0 To 4) As String
    Dim i As Long
 
    'put some values in the array for this example
    Stores(0) = "Open"
    Stores(1) = "Closed"
    Stores(2) = "Open"
    Stores(3) = "Open"
 
 
    For i = LBound(Stores) To UBound(Stores)
        If Stores(i) = "Open" Then
            MsgBox "Element " & i & " " & Stores(i)
        End If
    Next i
 
End Sub
 
Upvote 0
You're welcome. :)

Of course, there was a typo in the example I gave you. This line:
Code:
Dim Stores(0 To 4) As String
Should have read
Code:
Dim Stores(0 To 3) As String
 
Upvote 0

Forum statistics

Threads
1,222,558
Messages
6,166,779
Members
452,070
Latest member
patbrunner2001

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