2011-02-28 138 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,以满足您的数据。

相关问题