2017-10-09 47 views
0

我有一個宏,它根據項目#(列A)取出垃圾銷售。正如您在下面的代碼中看到的,有很多垃圾(需要刪除的行)項目編號以「40-xxxxx」開頭。我想結合這些循環,以便宏將刪除以「40-xxxxx」開頭的所有項目#除外「40-00017」&「40-00004」。結合多個For While While循環提高效率vba

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

試試這個。當刪除行而不是重置單元格時,更容易向後循環

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 
+0

不得不說,儘管用@ Coffeegrinder的方法(只要你沒有任何空白行)。 – SJR

1

改爲使用過濾器。你也可以使用宏記錄器。更簡單,更快捷。