结合多个For Do While循环以提高效率vba

时间:2017-10-09 15:22:21

标签: excel vba excel-vba

我有一个基于项目#(列A)取出垃圾销售的宏。正如您在下面的代码中看到的那样,有很多垃圾(需要删除的行)项目编号以“40-xxxxx”开头。我想组合这些循环,以便宏将删除以“40-xxxxx” EXCEPT “40-00017”开头的所有项目#& “40-00004”。

    sItem = Cells(I, 1)

    Do While Left(sItem, 8) = "40-00087" 'labor-annual refinish
        Rows(I).Select
        Selection.Delete shift:=xlUp
        sItem = Cells(I, 1)
    Loop
Next I

For I = 2 To nRowMax
    sItem = Cells(I, 1)

    Do While Left(sItem, 8) = "40-00076" 'CONNOISSEURS CLOTH
        Rows(I).Select
        Selection.Delete shift:=xlUp
        sItem = Cells(I, 1)
    Loop
Next I

For I = 2 To nRowMax
    sItem = Cells(I, 1)

    Do While Left(sItem, 8) = "40-00007" 'labor jewelery
        Rows(I).Select
        Selection.Delete shift:=xlUp
        sItem = Cells(I, 1)
    Loop
Next I

For I = 2 To nRowMax
    sItem = Cells(I, 1)

    Do While Left(sItem, 8) = "40-00073" 'foam cleaner blitz
        Rows(I).Select
        Selection.Delete shift:=xlUp
        sItem = Cells(I, 1)
    Loop
Next I

For I = 2 To nRowMax
    sItem = Cells(I, 1)

    Do While Left(sItem, 8) = "40-00084" 'labor-razny 1st
        Rows(I).Select
        Selection.Delete shift:=xlUp
        sItem = Cells(I, 1)
    Loop
Next I

For I = 2 To nRowMax
    sItem = Cells(I, 5)

    Do While Left(sItem, 2) = "GC" 'gift cards
        Rows(I).Select
        Selection.Delete shift:=xlUp
        sItem = Cells(I, 5)
    Loop
Next I

2 个答案:

答案 0 :(得分:2)

试试这个。删除行而不是重置单元格时更容易向后循环

Sub x()

Dim i As Long, nRowMax As Long

For i = nRowMax To 2 Step -1
    If Left(Cells(i, 1), 6) = "40-000" Then
        If Cells(i, 1).Value <> "40-00017" And Cells(i, 1).Value <> "40-00004" Then
            Cells(i, 1).EntireRow.Delete shift:=xlUp
        End If
    End If
Next i

End Sub

答案 1 :(得分:1)

请改用过滤器。您也可以使用宏录制器。更简单,更快捷。