Question

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

Était-ce utile?

La solution

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

Autres conseils

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top