Home » excel » vba – How to loop through the same cells in specified columns

vba – How to loop through the same cells in specified columns

Posted by: admin May 14, 2020 Leave a comment

Questions:

I wrote the following VBA to loop through the same cells in each column from column 2 to 1002. That is, in the coding, when i=2, I have Range(“B3”, “B1298”); when i=3, I need to have have Range(“C3”, “C1298”), and so on. How to achieve this, please? Thank you.

Sub ForwardRScen()

    Application.ScreenUpdating = False

    For i = 2 To 102

        Range("ChgBP").Value = Sheets("sth").Cells(2, i).Value
        Sheets("sth").Range("B3", "B1298").Value = Range("DResults").Value

    Next i

    Application.ScreenUpdating = True

End Sub
How to&Answers:

Assigning a range and changing it in the loop is a good way to go:

Public Sub TestMe()

    Dim i As Long
    For i = 2 To 12
        Dim myRange As Range
        Set myRange = Range(Cells(2, i), Cells(1298, i))
        myRange = i
    Next i

End Sub

This is what you will get:

enter image description here