2011-02-28 125 views
3

目前,我正在使用以下代碼來檢查某個單元格的A列中是否有#N/A值,如果找到,我將刪除該行。迭代範圍內的單元格

With Sheets(Sheet) 
     For LRow = 45 To 29 Step -1 
      With .Cells(LRow, "A") 
       If (CVErr(.Value) = CVErr(xlErrNA)) Then .EntireRow.Delete 
      End With 
     Next LRow 
    End With 

我需要擴展這個讓我檢查所有列1到10,而不是僅僅A.我想這輕微的修改(嵌套另一個循環),但它不工作。有什麼建議麼?

With Sheets(Sheet) 
     For LRow = 45 To 29 Step -1 
      For LCol = 10 To 1 Step -1 
       With .Cells(LRow, LCol) 
        If (CVErr(.Value) = CVErr(xlErrNA)) Then .EntireRow.Delete 
       End With 
      Next LCol 
     Next LRow 
    End With 

回答

2

兩個問題在這裏:

  • 的嵌套

  • 上任何給定行一次N/A

    被發現,你需要喲中止循環

試試

Set sh = Sheets(Sheet) 
For LRow = 45 To 29 Step -1 
    For LCol = 10 To 1 Step -1 
     If (CVErr(sh.Cells(LRow, LCol).Value) = CVErr(xlErrNA)) Then 
      sh.Cells(LRow, 1).EntireRow.Delete 
      Exit For ' Exit the LCol loop 
     End If 
    Next LCol 
Next LRow 
0

你可以採取一個稍微不同的方式

Sheets("Sheet1").Select 
Set cols = Range("A1:D80") 
For Each Cell In cols 
    If Cell.Value = "XXX" Then 
     Cell.EntireRow.Delete 
    End If 
Next 
+0

我收到一個'對象不支持屬性或方法在設置選擇線 – xbonez 2011-02-28 18:02:36

+0

您需要先選擇表 - 我已添加在 – 2011-02-28 18:04:53

+0

添加代碼以選擇工作表。同樣的錯誤。 – xbonez 2011-02-28 18:08:30

0

我相信有在「與」你使用條款嵌套的問題。

你可以定義一個適當的範圍並使用'for each'循環,這會使事情更清晰,更容易閱讀。爲了測試目的,我將範圍命名爲「MyRange」。

Sub test() 

    Dim cell As Excel.Range 

    For Each cell In [myRange] 

     If CVErr(cell.Value) = CVErr(xlErrNA) Then cell.EntireRow.Delete 

    Next cell 

End Sub 
2

這可能會在非英語

其他
Sub DeleteNA() 

    Dim rRange As Range 
    Dim rFound As Range 

    Const sNA As String = "#N/A" 

    Do 
     Set rRange = Sheet1.Range("A29:F49") 
     Set rFound = rRange.Find(sNA, , xlValues, xlWhole, xlByRows) 
     If Not rFound Is Nothing Then 
      rFound.EntireRow.Delete 
     Else 
      Exit Do 
     End If 
    Loop 

End Sub 

更改A29語言失敗:F49,以滿足您的數據。

相關問題