excel 在一次迭代后查找并删除端点

ecfdbz9o  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(82)

在A列中,我有以下从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
elcex8rz

elcex8rz1#

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

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

相关问题