Ori Meir
Ori Meir

Reputation: 51

Loop Without Do Error

I am trying to loop through three lists of data and hide the rows that have a total value of 0. Although I keep getting A "Loop Without Do" error, can someone spot what I have done wrong.

Cheers.

Sub Button1_Click()

Dim Brow1 As Integer
Dim Brow2 As Integer
Dim Brow3 As Integer

Dim Trow1 As Integer
Dim Trow2 As Integer
Dim Trow3 As Integer

Brow1 = 62
Trow1 = 3
Brow2 = 126
Trow2 = 67
Brow3 = 190
Trow3 = 131

Do While Brow1 > Trow1

    If Range("P" & Brow1).Value = 0 Then
        Rows(Brow1).EntireRow.Hidden = True

    ElseIf Range("P" & Brow1).Value <> 0 Then

       Brow1 = Brow1 - 1
Loop


Do While Brow2 > Trow2

    If Range("P" & Brow2).Value = 0 Then
        Rows(Brow2).EntireRow.Hidden = True

    ElseIf Range("P" & Brow2).Value <> 0 Then
       Brow2 = Brow2 - 1
Loop

Do While Brow3 > Trow3

    If Range("P" & Brow3).Value = 0 Then
        Rows(Brow3).EntireRow.Hidden = True

    ElseIf Range("P" & Brow3).Value <> 0 Then
       Brow3 = Brow3 - 1
Loop

End Sub

Upvotes: 0

Views: 5516

Answers (2)

ChipsLetten
ChipsLetten

Reputation: 2953

You are missing the End If part of every If statement.

You can also get rid of the Else If test and just use Else:

Do While Brow1 > Trow1
    If Range("P" & Brow1).Value = 0 Then
        Rows(Brow1).EntireRow.Hidden = True
    Else
       Brow1 = Brow1 - 1
    End If
Loop

You have another problem though. The first time you find Value = 0 you end up in an infinite loop because the value of Brow1 never gets reduced. A better version would be a For ... Next loop:

Dim i As Integer

For i = Brow1 To Trow1 Step -1
    If Range("P" & i).Value = 0 Then
        Rows(i).EntireRow.Hidden = True
    End If
Next i

Upvotes: 0

sous2817
sous2817

Reputation: 3960

None of your If statements are closed appropriately. Add an "End If" after each "ElseIF" and you should get your expected behavior:

Do While Brow1 > Trow1

    If Range("P" & Brow1).Value = 0 Then
        Rows(Brow1).EntireRow.Hidden = True

    ElseIf Range("P" & Brow1).Value <> 0 Then

       Brow1 = Brow1 - 1
    End If
Loop

Upvotes: 3

Related Questions