Frage

I have the below code in vba. The rows in sheet5 from columns a5 to a20 are:

a5=Sweden

a6=Spain

a7=Russia

a8=Italy

a9=Germany

a10=Finland

a11=Norway

a12=Switzerland

a13=France

a14=Belgium

Set fillcolumnrange = Sheet5.Range("A5:A20")
i = 1
For Each Row In fillcolumnrange.Rows
 If Not Sheet5.Range("A" & i + 4) = "" Then
    MsgBox Row(i)
 End If
 i = i + 1
Next Row

But this code is prompting only alternate values ie.

Sweden

Russia

Germany

Norway

France

Can anyone please help me out find the bug in the code

War es hilfreich?

Lösung

You were looping through the rows in your range and also advancing the variable i within your loop. You can reference each variable that you are looping through.

Try this

Set fillcolumnrange = Sheet1.Range("A5:A20")
For Each cell In fillcolumnrange.Cells
 If Not cell = "" Then
    MsgBox cell
 End If
Next cell

Andere Tipps

You've got a mixture of different types of loop.

Either do what Rick says.

Or use i:

Set fillcolumnrange = Sheet5.Range("A5:A20")
For i = 1 To fillcolumnrange.Rows.Count
    If Not Sheet5.Range("A" & i + 4) = "" Then
       MsgBox Sheet5.Cells(i + 4, 1)
    End If
Next i

Or maybe a do-Loop

Set fillcolumnrange = Sheet5.Range("A5:A20")
i = 1
do until i = fillcolumnrange.Rows.Count + 4
 If Not Sheet5.Range("A" & i + 4) = "" Then
    MsgBox Sheet5.Cells(i + 4, 1)
 End If
 i=i+1
Loop

(EDIT now tested and seem to run ok)

Building on Rick's answer, here's the short version of the For Each loop:

For Each cell in fillcolumnrange.Cells
    If len(cell) <> 0 Then MsgBox cell
Next
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top