Handle “No cells were found” error when filtered range is empty

前端 未结 4 1652
情深已故
情深已故 2020-12-17 04:56

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

myRange.SpecialCells(xlCellTypeVisible).Copy

As soon as the filter filters

相关标签:
4条回答
  • 2020-12-17 05:24

    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
    
    0 讨论(0)
  • 2020-12-17 05:34

    Got the same problem, but for filtering named table, solved it this way*:

    1. instead of applying several filters, I've added a column at the end of the table, with a formula that would return true for the rows I wanted to have filtered in, false for filtered out.
    2. Then, I've applied one filter for that true value and added a cell that would count all true values in that column
    3. in vba, firstly reapply filter for the table then if that counter is greater than 0 do .SpecialCells(xlCellTypeVisible).Copy, else skip to next step (i was doing that in a loop)

    *I know that this question is from 2015, but I've ended here in 2019 googling similar problem so I'm leaving my solution.

    0 讨论(0)
  • 2020-12-17 05:44

    What I do is I am counting filtered rows :

    Sheets("Sheet1").Range("A2:Z2").AutoFilter
    Sheets("Sheet1").Range("A2:Z2").AutoFilter Field:=1, Criteria1:=filter1
    If Sheets("Sheet1").AutoFilter.Range.Columns(4).SpecialCells(xlCellTypeVisible).Count > 1 Then
    

    you can change number of column to suits your needs

    0 讨论(0)
  • 2020-12-17 05:45
    On Error Resume Next
    Set rngFiltered = rngStart.SpecialCells(xlCellTypeVisible)
    On Error Goto 0
    
    If not rngFiltered is Nothing then
        rngFiltered.Copy
    End If
    
    0 讨论(0)
提交回复
热议问题