Home > Net >  Nested for loop exits to the parent loop before it completes
Nested for loop exits to the parent loop before it completes

Time:01-19

I have a nested for loop in VBA where I loop through all rows in a range and then within that I loop through all cells in the row. I want to add up the number of green cells in a row.

For Each r In rngData.Cells
    For Each c In r.Columns
        If c.Interior.Color = cGreen Then
            dur = dur   1
        End If
    Next c
dur = 0
Next r

The trouble is that after next c the code jumps down to next r so dur keeps getting reset to 0 where I want it to add up the number of green cells.

I would expect the code to complete the c loop before going to the next r loop. What am I not seeing?

CodePudding user response:

This is probably what you want:

For Each r In rngData.Rows
    For Each c In r.Cells
        If c.Interior.Color = cGreen Then
            dur = dur   1
        End If
    Next c
dur = 0
Next r
  • Related