如何使用excel VBA删除第一列包含某个代码的行?

How to delete a row that contains a certain code in the first column using excel VBA?

我每周 运行 报告,我必须采取的步骤是删除包含特定短语的行,在我的例子中 "CFS-GHOST-DJKT",在 A 列中。要通读的行从7 并且有一个可变的结尾。

我在网上看过,根据我的发现,下面的代码应该可以工作,但我得到了错误,它不喜欢 With Cells(Lrow,"A")

我认为就删除部分而言,它的编写方式还可以,但问题在于选择方面。

Firstrow = 7
Lastrow = Cells(Rows.Count, "A").End(xlUp).Row
    With Cells(Lrow, "A")
        If Not IsError(.Value) Then
            If .Value = "CFS-GHOST-DJKT" Then .EntireRow.Delete
       End If
    End With

删除时需要从最后一行迭代到第一行,否则最终会跳过行。

Dim x As Long
For x = Cells(Rows.Count, "A").End(xlUp).Row To 7 Step -1
    If Cells(x, "A") = "CFS-GHOST-DJKT" Then Rows(x).Delete
Next

根据您的叙述 ("I must ... delete a row"),您似乎只在意 "CFS-GHOST-DJKT"

这个短语

在这种情况下,无需遍历单元格,只需尝试找到它,如果成功,则删除其整行

    Dim f As Range

    Set f = Range("A7", Cells(Rows.Count, "A").End(xlUp)).Find(what:="CFS-GHOST-DJKT", LookIn:=xlValues, lookat:=xlPart)
    If Not f Is Nothing Then f.EntireRow.Delete