You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理VBA筛选删除行时出现的No Cells Found错误?

解决VBA「No Cells Found」错误:筛选并删除指定条件行(无符合项则跳过)

我在运行VBA代码时遇到「No Cells Found」错误,需求是筛选出满足指定条件的行,有符合条件的就删除,没有就直接跳过后续操作。试过用On Error Goto 0处理错误但还是触发报错,查了不少方案都不符合需求,希望能得到问题分析和修正方向。

原代码

Private Sub cmdGoLive_Click()
Dim rngFiltered As Range
lrow as long

On Error Resume Next

With myWorkbook.Worksheets("qryGoLive")
    lrow = .Cells(.Rows.Count, 1).End(xlUp).Row

'Filter by Color (Duplicates) then Filter by Offertype
    .Range("A2:P" & lrow).AutoFilter Field:=1, Criteria1:=RGB(255, 0, 0), Operator:=xlFilterCellColor
    .Range("A2:P" & lrow).AutoFilter Field:=16, Criteria1:="Promo"

'Delete Rows
Set rngFiltered = .Range("A2:P" & lrow).SpecialCells(xlCellTypeVisible).Row
    
    If Not rngFiltered Is Nothing Then
        .Cells(1, 1).Offset(1, 0).Resize(lrow - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    Else
    End If

'Unfilter Offertype and then color
    myWorkbook.Worksheets("qryGoLive").ShowAllData
End With
End Sub

问题分析

  • SpecialCells调用错误:SpecialCells(xlCellTypeVisible).Row只会返回第一个可见单元格的行号(数值类型),而非完整的区域对象。如果没有符合条件的行,这里触发错误后,rngFiltered会被赋值为错误值,后续If Not rngFiltered Is Nothing的判断完全失效。
  • 重复调用SpecialCells:删除行时再次调用SpecialCells,此时若没有可见行,会直接触发「No Cells Found」错误,错误处理逻辑没覆盖到这个环节。
  • 取消筛选的隐患:如果当前工作表没有处于筛选状态,调用ShowAllData会触发新的错误。

修正后的代码

Private Sub cmdGoLive_Click()
    Dim rngFiltered As Range
    Dim lrow As Long
    
    ' 仅捕获后续获取可见单元格的错误
    On Error Resume Next
    
    With myWorkbook.Worksheets("qryGoLive")
        lrow = .Cells(.Rows.Count, 1).End(xlUp).Row
        
        ' 筛选范围包含表头,确保筛选逻辑正常识别列
        .Range("A1:P" & lrow).AutoFilter Field:=1, Criteria1:=RGB(255, 0, 0), Operator:=xlFilterCellColor
        .Range("A1:P" & lrow).AutoFilter Field:=16, Criteria1:="Promo"
        
        ' 直接获取可见区域(排除表头行)
        Set rngFiltered = .Range("A2:P" & lrow).SpecialCells(xlCellTypeVisible)
        
        ' 关闭错误捕获,避免影响后续代码
        On Error GoTo 0
        
        ' 存在符合条件的行则删除
        If Not rngFiltered Is Nothing Then
            rngFiltered.EntireRow.Delete
        End If
        
        ' 安全取消筛选:先判断是否处于筛选状态
        If .AutoFilterMode Then
            .ShowAllData
        End If
    End With
End Sub

关键修正说明

  • 正确获取可见区域:直接将SpecialCells(xlCellTypeVisible)赋值给Range对象,无符合条件行时rngFiltered会是Nothing,判断逻辑正常生效。
  • 控制错误处理范围:在完成SpecialCells调用后立即关闭错误捕获,避免后续代码的错误被意外屏蔽。
  • 筛选范围包含表头:将筛选起始行从A2改为A1,确保Excel能正确识别表头并应用筛选。
  • 安全取消筛选:先检查AutoFilterMode状态,再执行ShowAllData,避免无筛选时触发错误。

内容的提问来源于stack exchange,提问作者Deke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 03:31:51