2017-04-20 71 views
1

我目前正在嘗試創建一個循環,將查看列C從第5行開始,並比較該列中的每個單元格,直到它到達該列中最後使用的單元格。 每個單元格將檢查8個變量,看它是否匹配。如果單元格不匹配任何變量,則必須刪除整行。VBA循環遍列來比較每個單元格與變量,並刪除該行,如果它不匹配

我現在的嘗試是這樣的:

Dim AC as long 
Dim LastRow as long 
AC=5 
LastRow= Activesheet.range("A" & Rows.count).end(xlup).row 
For AC = 5 To LastRow 
      With Cells(AC, "C") 
      Do Until Cells(AC, "C").Text = OC1 Or Cells(AC, "C").Text = OC2 Or Cells(AC, "C").Text = OC3 Or Cells(AC, "C").Text = OC4 Or Cells(AC, "C").Text = NC1 Or Cells(AC, "C").Text = NC2 Or Cells(AC, "C").Text = NC3 Or Cells(AC, "C").Text = NC4 
       Rows(AC).EntireRow.Delete 
      Loop 
     End With 
    Next AC 

這應該確保,一旦行已被刪除新的一行了它的位置(防爆刪除整個行5會導致第6行成爲第5行。 )所以它應該在出現匹配時退出Do循環,抓住下一個行號並重復,直到出現另一個匹配。只有代碼一直拋出執行中斷錯誤。有人可以告訴我我做錯了什麼嗎?

+0

是否真正產生一個錯誤,或做它會陷入無限循環? – YowE3K

回答

0

如果您的代碼導致無限循環,當你試圖殺死無限循環只產生你的錯誤,你可以使用下面的代碼:

Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 

Dim AC As Long 
Dim LastRow As Long 
AC = 5 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 
Do While AC <= LastRow 
    If Cells(AC, "C").Text <> OC1 And _ 
     Cells(AC, "C").Text <> OC2 And _ 
     Cells(AC, "C").Text <> OC3 And _ 
     Cells(AC, "C").Text <> OC4 And _ 
     Cells(AC, "C").Text <> NC1 And _ 
     Cells(AC, "C").Text <> NC2 And _ 
     Cells(AC, "C").Text <> NC3 And _ 
     Cells(AC, "C").Text <> NC4 Then 
     Rows(AC).Delete 
     LastRow = LastRow - 1 
    Else 
     AC = AC + 1 
    End If 
Loop 

Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 

與你目前的方式的問題做事情是這樣的,一旦你接近LastRow(假設你已經刪除了任何先前的行),你正在查看空行並因此無限刪除它們。


或者,當然了,你可以使用刪除行的更普遍接受的方式 - 這是在底部開始向上安裝:

Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 

Dim AC As Long 
Dim LastRow As Long 
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row 
For AC = LastRow To 5 Step -1 
    If Cells(AC, "C").Text <> OC1 And _ 
     Cells(AC, "C").Text <> OC2 And _ 
     Cells(AC, "C").Text <> OC3 And _ 
     Cells(AC, "C").Text <> OC4 And _ 
     Cells(AC, "C").Text <> NC1 And _ 
     Cells(AC, "C").Text <> NC2 And _ 
     Cells(AC, "C").Text <> NC3 And _ 
     Cells(AC, "C").Text <> NC4 Then 
     Rows(AC).Delete 
    End If 
Next 

Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 
+0

LastRow應該計算最後使用的行沒有工作表,我相信? 它也立即出錯,當我逐步瀏覽時,它仍然在第一行(第5行) – user7898186

+0

'LastRow'被計算爲包含列A中最後一個非空單元格的行。什麼錯誤是代碼生成? (它適用於我,但也許我的測試數據和實際數據之間有差異,導致它的問題。) – YowE3K

+0

我交換了我的代碼,它似乎現在工作。它必須經歷一個瘋狂的數據量,所以它需要運行一段時間。你的代碼與我的代碼相比是非常乾淨的,但是我仍然覺得我的代碼應該已經成功了...哪些不明白爲什麼我的代碼不工作會比我的代碼不工作lol – user7898186

相關問題