Loop not deleting all the required rows

时间:2019-03-19 15:06:46

标签: excel vba for-loop

My code is supposed to count the number of rows that are in the WIP worksheet and then loop through the rows and delete a row if its string in column B contains the word "out".

Sub delete()

numrows = Worksheets("WIP").Cells(Rows.Count, "A").End(xlUp).Row

For x = 1 To numrows

    If InStr(1, lCase(Range("B" & x)), "out") <> 0 Then
        Rows(x).Delete
    End If

Next

End Sub

The code is running without getting any errors but it only deletes some of the lines. Say there are 100 rows containing the word "out" in column B. I will run the code once and it will get rid of a few rows. Then I run it again and it gets rid of a few more. If I run the code enough times it will get rid of all the right rows.

I'm not sure why all the rows aren't deleting the first time around, any help would be much appreciated. Thanks.

4 个答案:

答案 0 :(得分:6)

Replace:

For x = 1 To numrows

with:

For x = numrows to 1 Step -1

The loop index gets corrupted if you run it forwards.

答案 1 :(得分:1)

您是否尝试过使用.FindNext?我认为这可能会更快一些,并且可以避免出现您的问题:

With sheets(“WIP”).Range(“B1:B” & x)

Set mycell = .Cells.Find(What:=“out”)

    If Not mycell Is Nothing Then

        Do Until mycell Is Nothing

            Cells(mycell.Row, “B”).entireRow.Delete

            Set mycell = .FindNext(mycell)
        Loop

End If

结尾

答案 2 :(得分:1)

我认为,处理大量数据时最有效的另一种方法是使用.ClearContents而不是.EntireRow.Delete,最后删除所有空白行。甚至更好,请考虑以下问题:

Columns("B:B").Replace What:="out", Replacement:=vbNullString, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
Columns("B:B").SpecialCells(xlCellTypeBlanks).EntireRow.delete

请注意,如果B为空,它将删除行,因此请调整您的数据,但这是最快的方法。

答案 3 :(得分:0)

While the best response is to loop backwards (thereby avoiding skipping over rows that have been shifted up when deleted), you could also nest in a Do While loop.

Option Explicit

Sub delete()

  dim x as long, numrows as long

  with Worksheets("WIP")

    numrows = .Cells(Rows.Count, "A").End(xlUp).Row

    For x = 1 To numrows

      Do While InStr(1, Range("B" & x), "out", vbTextCompare) > 0
        Rows(x).Delete
      Loop

    Next

  End With

End Sub