2016-08-05 45 views
0

我想根據每行中的值刪除具有多個表格的Excel表格中的表格中的行。經過大量研究和試驗和錯誤之後,我得到了我的宏,除非我必須多次運行它才能真正刪除所有「壞」行。這是我到目前爲止有:爲什麼我必須多次運行我的每個循環才能刪除表中的行?

Sub RemovePartsOfTable() 

Dim row As Range 

For Each row In ListObjects("Table6").DataBodyRange.Rows 

    If row.Columns(6).Value = "" Then 'to exit when it hits the end of the used cells 
     Exit For 

    ElseIf row.Columns(1).Value <> "P" And row.Columns(1).Value <> "B" _ 
     And row.Columns(2).Value <> "B" _ 
     And row.Columns(2).Value <> "P" Then 
     row.Delete 
    End If 

Next 

End Sub 

宏並刪除所有,我不想在表中,如果我跑五次行,但我寧可不要運行它不止一次因爲我正在構建此工作簿以供其他人使用。

+6

要麼運行一個反向循環,要麼將所有要刪除的行聯合起來並一次刪除。 – cyboashu

+0

在這裏看到許多您可以修改的方法:http://stackoverflow.com/questions/33744149/code-in-vba-loops-and-never-ends-how-to-fix-this –

+2

http:// stackoverflow。問題/ 20077945/delete-cells-in-excel-column-when-rows-0 –

回答

0

解決的辦法是將For循環放入Do循環中;那麼Do循環會重複,而在For循環中會執行一些刪除操作。

Option Explicit 

Sub RemovePartsOfTable() 
Dim flagNoRowDeletedInLoopCycle As Boolean 
Dim row As Range 

Do 

    flagNoRowDeletedInLoopCycle = False 

    For Each row In ActiveSheet.ListObjects("Table6").DataBodyRange.Rows 

     If row.Columns(6).Value = "" Then 'to exit when it hits the end of the used cells 

      Exit For 

     ElseIf row.Columns(1).Value <> "P" And row.Columns(1).Value <> "B" _ 
      And row.Columns(2).Value <> "B" _ 
      And row.Columns(2).Value <> "P" Then 

      row.Delete 

      flagNoRowDeletedInLoopCycle = True 

     End If 

    Next 

    If flagNoRowDeletedInLoopCycle = False Then Exit Do 

Loop 

End Sub 
+0

謝謝!這正是我正在尋找的那種修復。 – cscho

相關問題