Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle "No cells were found" error when filtered range is empty

Tags:

excel

vba

I do some filtering on a range and copy that filtered range with

myRange.SpecialCells(xlCellTypeVisible).Copy

As soon as the filter filters all cases I get

Error 1004 No cells were found

I am looking for a way to check (without an On Error) if the filtered range is empty.

I already tried to set a range with lastRow = .Cells(.Rows.Count, ColumnName).End(xlUp).Row and check if lastRow > 0 but with this way I also count the filtered (or hidden) row contents.

I also tried

Sub test()
    Dim rngStart As Range
    Dim rngFiltered As Range

    Set rngStart = Sheets(1).Range("A1:A6")
    Set rngFiltered = rngStart.SpecialCells(xlCellTypeVisible).Select

    If rngFiltered.Rows.Count = 0 Then
        MsgBox ("No Cases")
    Else
        MsgBox ("Found Cases")
    End If
End Sub

But here I get the error "No cells found" in the Set rngFiltered line as well.

I have no header row, since the filter is so complex that I programmed it without using the .Sort function

like image 287
ruedi Avatar asked Oct 21 '15 12:10

ruedi


2 Answers

Dim rngStart As Range
Dim rngFiltered As Range

'...
'...
Set rngFiltered = Nothing '<<< reset rngFiltered if running this code in a loop...
On Error Resume Next
Set rngFiltered = rngStart.SpecialCells(xlCellTypeVisible)
On Error Goto 0

If not rngFiltered is Nothing then
    rngFiltered.Copy
End If
'...
'...
like image 188
Tim Williams Avatar answered Sep 22 '22 08:09

Tim Williams


I stored the solution into a function. Here I use an error on mechamism.

Function errorCatchEmptyFilter(ByRef rngstart As Range) As Boolean

errorCatchEmptyFilter = False

'here I get an error if there are no cells
    On Error GoTo hell
    Set rngFiltered = rngstart.SpecialCells(xlCellTypeVisible)

Exit function

hell:
errorCatchEmptyFilter = True

End Function
like image 23
ruedi Avatar answered Sep 22 '22 08:09

ruedi