Currently, I'm using the following code to check column A in a certain range of cells for a #N/A value, and if found, I'm deleting that row.
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
I need to extend this so I check all columns 1 through 10, rather than just A. I tried this slight modification (nesting another loop), but it doesn't work. Any suggestions?
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
two issues here:
the nested with
on on any given row once N/A is found, you need yo abort the loop
try
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
This might fail in languages other than English
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
Change the A29:F49 to suit your data.
You could take a slightly different approach
Sheets("Sheet1").Select
Set cols = Range("A1:D80")
For Each Cell In cols
If Cell.Value = "XXX" Then
Cell.EntireRow.Delete
End If
Next
I believe there were problems in the nested 'with' clauses you used.
You could define a proper range and use a 'for each' loop, that would make things clearer and easier to read. I named a range as 'MyRange' for testing purposes.
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
精彩评论