[英]Iterate through cells in a range
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. 目前,我正在使用以下代码检查特定范围的单元格中的列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
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. 我需要扩展这个,所以我检查所有列1到10,而不是只是A.我尝试了这个小修改(嵌套另一个循环),但它不起作用。 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 一旦发现N / A,在任何给定的行上,你需要中止循环
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. 更改A29:F49以适合您的数据。
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. 我相信您使用的嵌套'with'子句存在问题。
You could define a proper range and use a 'for each' loop, that would make things clearer and easier to read. 您可以定义一个适当的范围并使用'for each'循环,这将使事情更清晰,更容易阅读。 I named a range as 'MyRange' for testing purposes.
为测试目的,我将范围命名为“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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.