Loop through variables which defined as range

blume77

New Member
Joined
Aug 26, 2019
Messages
1
Hello,
how can I loop through ranges. What I have already tried so far.
Is it possible?

Dim Variabel as Range
Dim Variabel_1 as Range
Dim Variabel_2 as Range
Dim Variabel_3 as Range
Dim I as Long

' the ranges are as an example
Set Variabel_1 = Range("A1")
Set Variabel_2 = Range("B5")
Set Variabel_3 = Range("C10")

For I = 1 to 3
Set Variabel = Range("Variabel_" & I) ' What is wrong with at this part?
next I
 

Excel Facts

Whats the difference between CONCAT and CONCATENATE?
The newer CONCAT function can reference a range of cells. =CONCATENATE(A1,A2,A3,A4,A5) becomes =CONCAT(A1:A5)
Hi, welcome to forum

Yes its possible -

If variables have same name the you could use an array

couple of ideas maybe

Code:
Sub Idea1()
    Dim Variable(1 To 3) As Range
    Dim i As Integer
    
    For i = 1 To 3
        Set Variable(i) = Range(Choose(i, "A1", "B5", "C10"))
        MsgBox Variable(i).Address
    Next i
End Sub


or

Code:
Sub Idea2()
    Dim Variable(1 To 3) As Range, rng As Range
    Dim i As Integer
    
    For Each rng In Range("A1, B5, C10")
        i = i + 1
        Set Variable(i) = rng
        MsgBox Variable(i).Address
    Next rng
End Sub

Others here may have alternative suggestions


Hope helpful


Dave
 
Upvote 0
Another way
Code:
Sub blume77()
   Dim Ary As Variant
   Dim i As Long
   
   Ary = Array("A1", "B5", "C10")
   For i = 0 To UBound(Ary)
      Range(Ary(i)).Interior.ColorIndex = i + 3
   Next i
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,236
Messages
6,170,917
Members
452,366
Latest member
TePunaBloke

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