VBA我的IF语句在找到一个迭代后结束

问题描述:

感谢您的阅读和您的帮助!VBA我的IF语句在找到一个迭代后结束

我有一个简单的问题,我只是无法弄清楚。

在列A I具有1以下的值至20。

1. NBC997 
2. EVO463 
3. EVO426 
4. EVO420 
5. EVO826 
6. EVO820 
7. EVO863 
8. CRO001 
9. BCA915 
10. SBH121 
11. KEN500 
12. GAM201 
13. GAM1011 
14. GAM101 
15. SPR577 
16. SPR580 
17. SPR579 
18. SPR576 
19. DON201 
20. MOR101 

我的以下公式应该看塔A ..和删除整个行,如果左2个字符<>“EV”。

无论出于何种原因,一旦它发现一个迭代..它完全停止,并不会去下一行。如果可以的话请帮忙。我知道我可能错过了一些非常愚蠢的事情。谢谢!

Sub remove() 

Dim i As Long 

    For i = 1 To 20 
     If Left(Cells(i, "A"), 2) <> "EV" Then 
     Cells(i, "A").EntireRow.Delete 
     Else 
    End If 
    Next i 

End Sub 
+7

环向后'对于i = 20〜1步-1' –

+0

你一定要循环向后因为集合每次重新编制了索引中删除行。但是,这并不能解释为什么你的循环显然只会执行一次,所以你可能需要进一步的调试... –

+0

向后循环是有道理的!谢谢! –

我不会使用删除整行。我会将数据向上移动一行,然后清除最后一行的内容。

Sub remove() 
Dim i As Long 
Dim x As Long 
Dim lastCol As Long 
Dim lastRow As Long 
Const dataColumn As Long = 1 
Const SearchPhrase As String = "EV" 
Const firstRow As Long = 1 
lastCol = Cells(firstRow, Columns.Count).End(xlToLeft).Column 
lastRow = Cells(Rows.Count, dataColumn).End(xlUp).Row 
    x = 0 
    For i = lastRow To firstRow Step -1 

    If Left(Cells(i, dataColumn), Len(SearchPhrase)) <> SearchPhrase Then 
     If i = lastRow Then 
      Range(Cells(lastRow, dataColumn), Cells(lastRow, lastCol)).ClearContents 
     Else 
      Range(Cells(i, dataColumn), Cells(lastRow - 1 - x, lastCol)).Value = _ 
      Range(Cells(i + 1, dataColumn), Cells(lastRow - x, lastCol)).Value 
      Range(Cells(lastRow - x, dataColumn), Cells(lastRow - x, lastCol)).ClearContents 
     End If 
     x = x + 1 
    End If 
    Next i 
End Sub 
+1

这将在技术上起作用,但通常不会将其视为改变迭代器值的最佳做法。从集合中删除项目时,最好向后迭代:) –

+0

谢谢,下次我会记住这一点;) –

+0

非常感谢您的帮助。我确实想完全删除该行,但这不是一个大问题。您的解决方案有效,非常感谢。 –