如果找到N / A,VBA excel代码删除行

时间:2012-05-16 04:36:56

标签: excel excel-vba vba

我正在寻找一种方法来查找整列中的N/A单元格,然后在找到N/A时删除整行。我找到了这个VBA代码,但它对我不起作用,因为它只选择一列。请帮助(我在Excel Mac 2011中处理大约300000行)

Sub DeleteBlankARows() 
    With Application 
        .Calculation = xlCalculationManual 
        .ScreenUpdating = False 
        Dim r As Long 
        For r = Cells(Rows.Count, 11).End(xlUp).Row To 1 Step -1 
            If Cells(r, 11) = "" Then Rows(r).Delete 
        Next r 
        .Calculation = xlCalculationAutomatic 
        .ScreenUpdating = True 
    End With 
End Sub 

2 个答案:

答案 0 :(得分:2)

另一种方法是使用Find来快速测试哪些单元格为NA()(我假设您正在测试=NA()作为公式单元格 - 如果是,我可以更新,或者也可以是文字)

此代码使用SpecialCells仅搜索错误值。

Sub GetNA()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim strFA As String

On Error Resume Next
Set rng1 = ActiveSheet.UsedRange.SpecialCells(xlFormulas, xlErrors)
On Error GoTo 0

If rng1 Is Nothing Then
    MsgBox "No NA() cells"
    Exit Sub
End If

With rng1
    Set rng2 = .Find("=NA()", LookIn:=xlFormulas)
    If Not rng2 Is Nothing Then
        strFA = rng2.Address
        Set rng3 = rng2.EntireRow
        Do
            Set rng2 = .FindNext(rng2)
            Set rng3 = Union(rng3, rng2.EntireRow)
        Loop While Not rng2 Is Nothing And rng2.Address <> strFA
    End If
    If Not rng3 Is Nothing Then rng3.Delete
End With

End Sub

答案 1 :(得分:1)

试试这个(在Windows XP / Excel 2007上测试但它应该适用于Mac / Office 2011):

Option Explicit

Sub DeleteNARows()
    Dim r As Long
    Dim iCol As Long
    With Application
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
        .DisplayAlerts = False
        For iCol = 1 To Cells(1, Columns.Count).End(xlToLeft).Column
            For r = Cells(Rows.Count, iCol).End(xlUp).Row To 1 Step -1
                If Application.WorksheetFunction.IsNA(Cells(r, iCol)) Then Rows(r).Delete
            Next r
        Next iCol
        .Calculation = xlCalculationAutomatic
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With
End Sub

请注意,您可以(并且可能必须)更改要在代码开头检查fot #N/A的列