目前,我正在使用以下代码检查特定范围的单元格中的列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
答案 0 :(得分:2)
这里有两个问题:
嵌套
在任何给定的行上,你需要中止循环
试
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
答案 1 :(得分: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以适合您的数据。
答案 2 :(得分: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
答案 3 :(得分:0)
我相信您使用的嵌套'with'子句存在问题。
您可以定义一个合适的范围并使用'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