Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested for loop exits to the parent loop before it completes

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading