excel 在应用筛选器之前检查筛选器值是否存在

tzdcorbm  于 2023-05-01  发布在  其他
关注(0)|答案(1)|浏览(151)

我有一个宏通过一个助手列过滤掉特定的记录,然后将任何过滤的行复制/粘贴到另一个工作表。帮助列返回0(不适用)或1(适用),宏应该复制标记为“1”的所有记录。
问题是,如果我在helper列中没有“1”记录,宏将所有“0”(=所有条目)复制到新工作表,很可能是因为它找不到任何值为“1”的记录。
如何在应用过滤器之前检查helper列是否有带“1”的记录?最好是,如果没有带有“1”的记录,我跳过整个with,并继续代码的下一步。

With ThisWorkbook
    ' track last row for comment insert
    lastrow_fb = Sheets("Monthly Comments").Range("C65536").End(xlUp).Offset(1).Row
    
    ' filter all records where helper column has value "1"
    .Sheets(DataYear & "_YTD").Range("SY2").AutoFilter Field:=519, Criteria1:="1"
    
    ' copy meta data
    .Sheets(DataYear & "_YTD").Range("F3:I" & lastrow).Copy
    .Sheets("Monthly Comments").Range("C" & lastrow_fb).PasteSpecial xlValues
    
    ' copy positive highlight
    .Sheets(DataYear & "_YTD").Range("CI3:CI" & lastrow).Copy
    .Sheets("Monthly Comments").Range("C" & lastrow_fb).Offset(0, 4).PasteSpecial xlValues
    
    ' copy negative improvement suggestion
    .Sheets(DataYear & "_YTD").Range("CK3:CK" & lastrow).Copy
    .Sheets("Monthly Comments").Range("C" & lastrow_fb).Offset(0, 5).PasteSpecial xlValues
    
    ' write outlet name
    .Sheets("Monthly Comments").Range(Range("B65536").End(xlUp).Offset(1), Range("C65536").End(xlUp).Offset(0, -1)).Value = "Name"
    
    ' unset helper column filter for next loop
    .Sheets(DataYear & "_YTD").Range("SY2").AutoFilter Field:=519
End With
oknrviil

oknrviil1#

存在许多方法来确定滤波器范围中的滤波元素的数量和/或存在。下面是其中的一些

Sub CheckFilter()
    Dim af As AutoFilter, filter_body_range As Range, rng_to_copy As Range
    
    Set af = ThisWorkbook.Sheets(1).AutoFilter
    Set filter_body_range = Intersect(af.Range, af.Range.Offset(1))
    
    ' option 1
    Set rng_to_copy = Nothing
    On Error Resume Next
    Set rng_to_copy = filter_body_range.SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    If Not rng_to_copy Is Nothing Then
        rng_to_copy.Copy
        Debug.Print "Visible rows in the filter range has been copied: address " & rng_to_copy.Address
        ' paste to the target place
    End If
    
    'option 2
    m = Application.Match(1, filter_body_range.Columns(5), 0)
    If IsNumeric(m) Then
        Debug.Print "The 5 column has value 1"
        ' your code to copy/paste
    End If
    
    ' option 3
    filtered_rows = 0
    On Error Resume Next ' switch off system error handling: if no xlCellTypeVisible cells, error occurs
    filtered_rows = filter_body_range.Columns(1).SpecialCells(xlCellTypeVisible).Count
    On Error GoTo 0 'switch on system error handling
    If filtered_rows > 0 Then
        Debug.Print "Filtered range has " & filtered_rows & " visible rows"
        ' your code to copy/paste
    End If
End Sub

图纸:

Visible rows in the filter range has been copied: address $C$7:$L$7,$C$13:$L$17,$C$24:$L$26
The 5 column has value 1
Filtered range has 9 visible rows

相关问题