【问题标题】:Excel VBA Macro to delete N/A rows删除 N/A 行的 Excel VBA 宏
【发布时间】:2022-11-17 19:56:51
【问题描述】:

我有一个带有多个选项卡的 Excel 工作簿,我希望在打开时运行一个宏,以删除其中包含 N/A 错误的任何行。有人可以帮忙吗?我尝试了以下但我需要它在打开时运行,并且还需要它根据任何列中的 NA 删除,而不仅仅是 A.

Sub RowKiller()
    Dim N As Long, NN As Long
    Dim r As Range
    NN = Cells(Rows.Count, "A").End(xlUp).Row
    Dim wf As WorksheetFunction
    Set wf = Application.WorksheetFunction
    For N = NN To 1 Step -1
        Set r = Cells(N, "A")
        If wf.CountA(r) = 1 And wf.CountA(r.EntireRow) = 1 Then
            r.EntireRow.Delete
        End If
    Next N
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    这是一个通用函数,可用于查找指定范围内的#N/A 错误并删除行。我还包括了一个更短的函数,如果使用它,它会删除任何错误行。

    该函数找到有错误的范围子集,然后测试单元格值是否为 #N/A 错误。这应该比测试使用范围内的每个单元格更快。

    .SpecialCells(xlConstants, xlErrors) 可能是多余的,可以简化功能,但我不知道所有导致 #N/A 的用例都包括在内以确保完整性。

    https://support.microsoft.com/en-us/office/automatically-run-a-macro-when-opening-a-workbook-1e55959b-e077-4c88-a696-c3017600db44

    Sub Foo()
        Call ErrorRowKiller(ActiveSheet.UsedRange)
    End Sub
    
    Function ErrorRowKiller(ErrorArea As Range)
        On Error Resume Next
        Dim R1, R2, Rall, Cell, ToKill As Range
        With ErrorArea
            Set R1 = .SpecialCells(xlConstants, xlErrors)
            Set R2 = .SpecialCells(xlFormulas, xlErrors)
        End With
        
        If R1 Is Nothing Then
            Set Rall = R2
        Else
            Set Rall = IIf(R2 Is Nothing, R1, Application.Union(R1, R2))
        End If
        
        For Each Cell In Rall
            If Application.WorksheetFunction.IsNA(Cell) = True Then
                If ToKill Is Nothing Then
                    Set ToKill = Cell
                Else
                    Set ToKill = Application.Union(ToKill, Cell)
                End If
            End If
        Next Cell
        
        ToKill.EntireRow.Delete
        
    End Function
    
    Function ErrorRowKiller2(ErrorArea As Range)
        On Error Resume Next
        With ErrorArea
            .SpecialCells(xlConstants, xlErrors).EntireRow.Delete
            .SpecialCells(xlFormulas, xlErrors).EntireRow.Delete
        End With
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-21
      相关资源
      最近更新 更多