我正在尝试编写一个宏,如果在给定范围内的单元格= 0,将删除一行。我遇到的问题是,当For Each循环运行时,它将找到单元格并删除该行,但如果它下面的行也有一个0,它最终会被代码跳过,因为代码已经移动到下一个范围。我希望有一个宏将在一系列单元格中找到0,并将在该范围内循环,该范围为0,直到该单元格大于0。 我已将此作为正在进行的工作......
Sub Pub_Clean()
Dim IRange As Range
Dim VRange As Range
Set VRange = Range(ActiveSheet.Range("b3"), ActiveSheet.Range("b3").End(xlDown))
For Each IRange In VRange
If IRange = 0 Then
IRange.EntireRow.Delete
End If
Next IRange
End Sub
答案 0 :(得分:4)
删除时,典型的方法是从底部开始并循环。这需要索引指定的循环,而不是FOR EACH。以下是一些细节:
For I=TotalRows To 1 Step -1
Set c = Range("C" & I)
' code to check for criteria and delete if required
Next I
答案 1 :(得分:0)
对行执行操作的最快方法是运行自动过滤器并使用specialcells(xlcelltypevisible)
。循环,尤其是删除行的循环要慢得多。在您的情况下,这是更新:
Sub Pub_Clean()
Dim VRange As Range
Set VRange = Range(ActiveSheet.Range("b2"), ActiveSheet.Range("b2").End(xlDown))
with VRange
.autofilter
.autofilter field:=1, criteria1:="0"
.resize(.rows.count-1).offset(1).specialcells(xlcelltypevisible).entirerow.delete
.autofilter
End with
End Sub
答案 2 :(得分:0)
对于大多数情况,其他答案都是正确且有用的 - AutoFilter非常快,自下而上的循环在删除行时没有问题 - 但在某些情况下,您可能需要一个从顶部到底强>
在这种情况下,有两个重要步骤:
包含两列和十行的示例,其中第一列包含各种数字,并且应删除此列中所有为零的行:
Sub DeleteRowWithLoop()
' Define start and end row numbers
Dim lastRow As Long
Dim i As Long
i = 1
lastRow = 10
' Use while loop to enable dynamic change of lastRow
While i <= lastRow
' Get current row to work on
Dim currentRow As Range
Set currentRow = Range(Cells(i, 1), Cells(i, 2))
' Delete whole row if first column contains zero
' Next and last cell numbers will have to be decreased
If (Cells(i, 1).Value = 0) Then
i = i - 1
lastRow = lastRow - 1
currentRow.EntireRow.Delete
End If
' Increment while counter/current row number (even if nothing was deleted)
i = i + 1
Wend
End Sub