简体   繁体   中英

For loop with multiple ranges ? VBA

I would like to do a for loop with multiple ranges, but i can't find a way with the "set" range as can you help me?

Here my code with one range:

Dim mycell As Range
Dim myrange As Range
    
Set myrange = src.Worksheets("Feuil1").Range("G1:500")
    
For Each mycell In myrange
        data = mycell.Value
Next mycell

but how can I do with two ranges at the same times in the for loop and after one range in a if condition and another in another if condition?

If you want to loop over two distinct (same-size) ranges then you can use a For...Next loop:

Dim i As Long, data1, data2
Dim myrange1 As Range, myrange2 As Range
    
Set myrange1 = src.Worksheets("Feuil1").Range("G1:G500")
Set myrange2 = src.Worksheets("Feuil1").Range("J1:J500")
    
For i = 1 to myrange1.Cells.Count
    data1 = myrange1.Cells(i).Value
    data2 = myrange2.Cells(i).Value
    'do something with data1 and data2
Next i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM