2012-05-16 32 views
1

我正在尋找一種方法來查找整個列中的N/A單元格,然後刪除整個行,如果找到N/A。我發現這個VBA代碼,但它不適合我,因爲它只選擇一列。請幫助(我周圍的30萬行Excel中的Mac 2011工作)VBA excel代碼刪除行,如果發現N/A

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 

回答

1

試試這個(測試在Windows XP/Excel 2007中,但它應該在Mac /辦公室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在代碼的開頭

+0

謝謝!但我怎麼能讓它自動運行並檢查所有列?因爲我有直到UH列! – soso101

+0

我編輯了我的代碼來處理每一列 – JMax

+0

+1很好處理 – brettdj

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 
+0

,那麼你可以試試並提出一個新問題。如果沒有太多的#N/A但是需要檢查大量的單元格,這可能會更快。然而,我讀過['find'似乎很慢](http://fastexcel.wordpress.com/2011/10/26/match-vs-find-vs-variant-array-vba-performance-槍戰/) – JMax

+0

+ 1像往常一樣好:) –

+2

@JMax這是從查爾斯的好鏈接。但正如文章所述,Find是一種多列搜索的方式(並且可以處理部分匹配,區分大小寫,格式匹配等 - 這使得它比其他方法更通用)。雖然對於單列搜索AutoFilter是文章中值得注意的一個例外 – brettdj