0

I'm having trouble with my i loop. For some reason, my loop only goes through the first iteration (i=0) and then stops. Here is my code:

Private Sub DeleteFillerRows()

Dim firstRow As Integer
Dim lastRow As Integer
Dim searchRange As Range

Dim i As Integer
For i = 0 To i = 2
    If i = 0 Then
        lastRow = 1
    End If

    MsgBox (i) 'used for testing, only displays the first i (0)

    Set searchRange = Range("A" & CStr(lastRow) & ":A1000")

    firstRow = searchRange.Find(What:="Name /", LookAt:=xlWhole).Row
    MsgBox (firstRow)

    lastRow = searchRange.Find(What:="Region 1", LookAt:=xlWhole).Row - 2
    MsgBox (lastRow)
Next i

End Sub

Can anyone help me with this? I feel dumb asking about a simple i loop but I just can't see where I could have gone wrong.

GT.
  • 764
  • 1
  • 8
  • 30

1 Answers1

4

A For loop is bounded like this:

For <counter> = <start> To <end>

In your case, <counter> is the variable i, <start> is 0, and <end> is the expression i = 2.

The reason why it only executes once is because the expression i = 2 evaluates as a Boolean, and it's always false because the initializer for the loop sets it to 0 (which is False).

If you rewrite your code with parentheses for grouping, it is a lot clearer what is going on:

For i = 0 To (i = 2)

...becomes...

For i = 0 To False

...which is...

For i = 0 To 0

As @ScottCraner correctly points out in the comments, simply correct the line to:

For i = 0 to 2

Comintern
  • 21,855
  • 5
  • 33
  • 80