【问题标题】:Clear Contents of Visible Cells in Filtered Column清除过滤列中可见单元格的内容
【发布时间】:2019-06-17 14:05:29
【问题描述】:

我正在过滤一个辅助单元格以定位 B 列中需要清除内容的单元格。一旦我过滤了已识别 B 列中需要清除内容的单元格的辅助单元格,我在清除该单元格中的内容时遇到问题。

除了我无法弄清楚如何仅从第一个可见单元格开始到最后一个可见单元格来清除可见单元格之外,我大致了解了这一点。我的问题是确定应用过滤器后第一个可见单元格的开始位置以及最后一个可见单元格的位置。

Sub Macro1()
'
' Macro1 Macro

Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell1 As Range
    Set wb = ActiveWorkbook
    Set ws = ActiveSheet

'This identifying the row of the last cell to filter on
Const WHAT_TO_FIND1 As String = "Tango"
Set FoundCell1 = ws.Range("AX:AX").Find(What:=WHAT_TO_FIND1)


'This is filtering on the helper cell to determine what cells need to be cleared.
ws.Range("$BA$8:$BA$" & FoundCell1.Row).AutoFilter Field:=1, Criteria1:= _
    "Delete"

'This is where I'm having issues.  I would like to replace B2 with a more dynamic code 
'that finds the first visible cell after the filter is applied and start there.  
'I think the xlUp solves the issue of finding the last visible cell but I am not sure 
'if that is the best or correct method.
ws.Range("B2:B" & Rows.Count).End(xlUp).SpecialCells(xlCellTypeVisible).ClearContents
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我会这样做:

    Sub tgr()
    
        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell1 As Range
    
        Set wb = ActiveWorkbook
        Set ws = wb.ActiveSheet
    
        'This identifying the row of the last cell to filter on
        Const WHAT_TO_FIND1 As String = "Tango"
        Set FoundCell1 = ws.Range("AX:AX").Find(What:=WHAT_TO_FIND1)
        If FoundCell1 Is Nothing Then Exit Sub  'WHAT_TO_FIND1 not found
    
        'This is filtering on the helper cell to determine what cells need to be cleared.
        With ws.Range("$BA$8:$BA$" & FoundCell1.Row)
            If .Row < 8 Or .Rows.Count = 1 Then Exit Sub   'No data
    
            .AutoFilter Field:=1, Criteria1:="Delete"
            On Error Resume Next    'Suppress error in case there are no visible cells
            Intersect(.Worksheet.Columns("B"), .Offset(1).Resize(.Rows.Count - 1).EntireRow).SpecialCells(xlCellTypeVisible).ClearContents
            On Error GoTo 0         'Remove "On Error Resume Next" condition
            .AutoFilter
        End With
    
    End Sub
    

    【讨论】:

    • 感谢您的代码 Tiger。我尝试了您的代码,似乎自动过滤器正在过滤 A 列而不是 BA ......这没有意义,因为代码看起来正在引用 BA。我之前也遇到过这个问题,我引用了要过滤的 BA,但它一直在过滤 A。起初我以为这只是我的代码,但这是 Excel 中的一个小故障吗?
    • @JDoe 我无法复制这种行为。它为我正确过滤了 BA 列。
    • 啊,我明白了,这是我的问题。有一个空行将标题与辅助行中的其余单元格分开,导致此问题。我只需在空行中插入内容即可将标题连接到辅助列中的其余数据,并且您的宏运行完美。非常感谢!
    猜你喜欢
    • 2018-07-08
    • 2012-12-19
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多