Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying the iteration of a For Each loop in VBA?

If I have a loop that commences:

For each c in Range("A1:C8")

Is there a property of the placeholder c (c.count, c.value, c.something,...) that identifies the number of times the loop has iterated thus far? I would rather use something like this than including another variable.

like image 343
GrahamD Avatar asked Feb 15 '13 00:02

GrahamD


2 Answers

Instead of using a "for each c in range" you can do something like this:

Dim c as Long 'presumably you did this as a Range, just change it to Long.
Dim myRange as Range 'Use a range variable which will be easier to call on later
Set myRange = Range("A1:C8")

For c = 1 to myRange.Cells.Count
    'Do something to the cell, identify it as myRange.Cells(c), for example:
    myRange.Cells(c).Font.Bold = True   '<--- replace with your code that affects the cell
Next

This allows you to do the exact same For/Next loop, without including an unnecessary counter variable. In this case, c is a counter but also serves the purpose of identifying the cell being impacted by the code.

like image 108
David Zemens Avatar answered Sep 24 '22 19:09

David Zemens


You need to count it yourself like this

Dim i as integer
i = 0    
For each c in Range("A1:C8")
    i = i + 1

Or

Dim i as integer
Dim c as Range
For i = 0 to Range("A1:C8").Count - 1
    Set c = Range("A1:C8").Cells(i)
like image 30
Dale M Avatar answered Sep 21 '22 19:09

Dale M