Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through each cell in a range of cells when given a Range object

Tags:

excel

vba

Let's say I have the following code:

Sub TestRangeLoop()     Dim rng As Range     Set rng = Range("A1:A6")      ''//Insert code to loop through rng here End Sub 

I want to be able to iterate through a collection of Range objects for each cell specified in rng. Conceptually, I'd like to do it like so:

For Each rngCell As Range in rng      ''//Do something with rngCell Next 

I know I could solve this by parsing rng.Address and building Range objects manually, but I'm hoping there is a more direct way that doesn't involve string parsing.

like image 712
Ben McCormack Avatar asked Oct 06 '10 17:10

Ben McCormack


People also ask

How do you loop through a range of cells?

One way to loop through a range is to use the For... Next loop with the Cells property. Using the Cells property, you can substitute the loop counter (or other variables or expressions) for the cell index numbers. In the following example, the variable counter is substituted for the row index.

How do you loop through all cells Excel?

Press F5 key to begin looping the column, then the cursor will stop at the first met blank cell.


2 Answers

Sub LoopRange()      Dim rCell As Range     Dim rRng As Range      Set rRng = Sheet1.Range("A1:A6")      For Each rCell In rRng.Cells         Debug.Print rCell.Address, rCell.Value     Next rCell  End Sub 
like image 82
Dick Kusleika Avatar answered Oct 11 '22 23:10

Dick Kusleika


You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()      Dim rCell As Range     Dim rRng As Range      Set rRng = Sheet1.Range("A1:A6")      For Each rCell In rRng.Rows         Debug.Print rCell.Address, rCell.Value     Next rCell  End Sub 

And Columns:

Sub LoopRange()      Dim rCell As Range     Dim rRng As Range      Set rRng = Sheet1.Range("A1:A6")      For Each rCol In rRng.Columns         For Each rCell In rCol.Rows             Debug.Print rCell.Address, rCell.Value         Next rCell     Next rCol  End Sub 
like image 33
code4life Avatar answered Oct 12 '22 01:10

code4life