2017-04-17 108 views
3

我有一個子過程刪除包含大約1000行的範圍中的行。 行在critera上被刪除。下面的代碼工作。Excel VBA刪除for循環中的行缺失行

但是,當我運行宏時,通常必須在刪除包含刪除條件的所有行之前運行它4次。

我想這是因爲for循環在刪除一行時突然消失的情況下會錯過它的索引。

我的第一個代碼看起來像這樣。

Set StatusRange = Range("B2", Range("B2").End(xlDown)) 

     For Each StatusCell In StatusRange 
        If StatusCell = "FG" Then 
         StatusCell.EntireRow.Delete 
        ElseIf StatusCell = "QC" Then 
         StatusCell.EntireRow.Delete 
        ElseIf StatusCell = "CS" Then 
         StatusCell.EntireRow.Delete 
        Else 
       End If 
    Next StatusCell 

當我嘗試更新範圍每個循環,它仍然無法正常工作。

Set StatusRange = Range("B2", Range("B2").End(xlDown)) 
    For Each StatusCell In StatusRange 
      If StatusCell = "FG" Then 
       StatusCell.EntireRow.Delete 
      ElseIf StatusCell = "QC" Then 
       StatusCell.EntireRow.Delete 
      ElseIf StatusCell = "CS" Then 
       StatusCell.EntireRow.Delete 
      Else 
     End If 

     Set StatusRange = Range("B2", Range("B2").End(xlDown)) 
     Next StatusCell 

有沒有人知道這個問題?謝謝。

+1

從德自下而上的工作。如果你刪除一行,一切都向上移動並昱歐上跳過該行下一次迭代 – Jeeped

+1

這幾乎肯定是一個重複的問題,當我找到合適的重複項時,我會將其標記爲這樣。無論何時從集合中刪除項目,您都必須從Rows.Count中刪除1 Step -1 ''否則你會跳過行。 –

+0

繼續前進,並認爲這@DavidZemens - 我已經通過顯示Case語句進行多重比較增加了一些價值,但這仍然是一個騙局。 – Jeeped

回答

6

從下往上工作。如果刪除一行,則所有內容都會向上移動,並在下一次迭代中跳過該行。

下面是從底部開始工作的代碼的'膽量'。

With Worksheets("Sheet1") 
    For rw = .Cells(.Rows.Count, "B").End(xlUp).Row To 2 Step -1 
     Select Case UCase(.Cells(rw, "B").Value2) 
      Case "FG", "QC", "CS" 
       .Rows(rw).EntireRow.Delete 
     End Select 
    Next rw 
End With 
+0

我正在寫字面相同的答案(完成與'Case'語句)哈哈:D –

+0

該死的,我剛剛完成鍵入和張貼幾乎完全相同的代碼;) –

1

由於是爲For Each你需要使用一個稍微不同的方法沒有反向循環。

而且,你的代碼有多個If S和OR是「尖叫的使用Select Case

Dim StatusRange As Range 
Dim i As Long 

Set StatusRange = Range("B2", Range("B2").End(xlDown)) 

' loop backward when deleting Ranges, Rows, Cells 
For i = StatusRange.Rows.Count To 1 Step -1 
    Select Case StatusRange(i, 1).Value 
     Case "FG", "QC", "CS" 
      StatusRange(i, 1).EntireRow.Delete 
     Case Else ' for the future if you need it 

    End Select 
Next i