'Won't "Exit Do" when condition is thought to be met after looping

Loop is to continue until the filtering of the table results in no visible rows (Table has no blanks). Then it is supposed to exit.

If it finds visible rows, it operates properly and performs the Else condition. It should do this and then loop through again until the filtering returns no visible rows. e.g. pVisible should eventually become nothing.

What's happening: If it initially filters and pVisible is found to be not nothing it performs the else and loops but once the filtering returns no rows, it keeps performing the else when I am expecting it to Exit Do.

Do

Sheet8.Activate

' Independent Check and Add
With Sheet8.ListObjects("Table1")

    .AutoFilter.ShowAllData
    .Range.AutoFilter Field:=23, Criteria1:="0"
    .Range.AutoFilter Field:=22, Criteria1:="Independent"
    
    On Error Resume Next 'ignore error if no visible rows
    Set pVisible = .DataBodyRange.SpecialCells(xlCellTypeVisible) 'ignore headers
    On Error GoTo 0      'stop ignoring errors
    
End With

If pVisible Is Nothing Then
 
    Exit Do
    
Else
    
    With Worksheets("Roster").AutoFilter.Range

        Range("A" & .Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row).Select
        Range(Selection, Selection.Offset(, 1)).Copy
        
        Worksheets("Add Names").Activate
        Worksheets("Add Names").Range("A3").PasteSpecial Paste:=xlPasteValues
        Range("A3:B3").Select
        Selection.AutoFill Destination:=Range("A3:B" & Range("C" & Rows.Count).End(xlUp).Row)
        
        Range("A3:D" & Range("A3").End(xlDown).Row).Select
        Selection.Copy
        
        Worksheets("Committee Table").Activate
        Sheet1.ListObjects("CredDB").AutoFilter.ShowAllData
        Range("A14").End(xlDown).Offset(1, 0).Select
        Selection.PasteSpecial Paste:=xlPasteValues
        
    End With
    
End If

Loop


Solution 1:[1]

When you bypass an error pVisible remains the same. It does not change to Nothing.

A possible quick and dirty way is, just before On Error GoTo 0.

If err > 0 then Set pVisible = Nothing

If you rearrange the logic you need not test pVisible.

If err > 0 then Exit Do

As indicated in a comment "The conventional approach is to put Set pVisible = Nothing before On Error Resume Next".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1