用于删除N/A行的Excel VBA宏

holgip5t  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(463)

我有一个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
g2ieeal7

g2ieeal71#

下面是一个通用函数,可以用来查找指定范围内的#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 As Range, R2 As Range, Rall As Range, Cell As Range, 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

相关问题