我有一个for循环,它遍历表中的所有值,并且应该删除所有表示no的行,但是它只删除每隔一行。我放了一个只有1-30号的专栏,我清楚地看到11,13,15,17,19,21等说不,但没有被删除。为什么它只删除每隔一行?
编辑 - 向后循环它有同样的问题
currRow = 1
currCell = Cells(currRow, 21).Value
For i = 1 To 30
If currCell = "no" Then
Rows(currRow).EntireRow.Delete
End If
currRow = currRow + 1
currCell = Cells(currRow, 21).Value
Next i
答案 0 :(得分:2)
您可以后退并删除行。此外,您For...Next
语句中的方法已关闭。
您说If currCell = "no"
,但currCell
在您检查行i
之后才会更新。
完全摆脱那个变量。
此外,还要删除currRow
变量。
Dim i As Long, ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
For i = 30 To 1 Step -1
If ws.Cells(i, 21).Value = "no" Then
ws.Rows(i).EntireRow.Delete
End If
Next
你不必倒退。创建一个特殊的范围对象来跟踪要删除的行,然后一次删除它们:
Dim i As Long, ws As Worksheet, delRng As Range
Set ws = ThisWorkbook.Worksheets(1)
For i = 1 To 30
If ws.Cells(i, 21).Value = "no" Then
If delRng Is Nothing Then
Set delRng = ws.Rows(i)
Else
Set delRng = Union(delRng, ws.Rows(i))
End If
End If
Next
If Not delRng Is Nothing Then delRng.Delete