views:

2195

answers:

2

I want to process every element of a for-loop. Taking this code, why is just every second element processed?

For Each row In ws.Rows
    If IsEmpty(row.Cells(row.row, 1)) Then
        Exit For
    Else
        MsgBox row.Cells(row.row, 1).value
    End If
Next

Thanks in advance for your answers!

+2  A: 

Instead of refering to Row.Cells refer to Worksheet.Cells. Also, you might want to select the ActiveRange of the worksheet, that should prevent a lot of useless Rows in your for-each.

Check out MSDN for examples on this.

Zyphrax
UsedRange, not ActiveRange.
Gary McGill
A: 

Setting ws to a Range with the range of cells B1:B10 which contain the values 1-10 respectively will produce the desired result:

Sub Macro1() Dim ws As Range

Set ws = Range("B1:B10")

For Each Row In ws.Rows

If IsEmpty(ws.Cells(Row.Row, 1)) Then
    Exit For
Else
    MsgBox ws.Cells(Row.Row, 1).Value
End If

Next

End Sub

amarcy