如何使用excel VBA删除第一列中包含特定代码的行?

时间:2016-11-06 02:37:42

标签: excel vba excel-vba delete-row

我每周都会运行一个报告,我必须采取的步骤是删除包含某个短语的行,在我的情况下" CFS-GHOST-DJKT",在A列。要读取的行在7,并有一个变量结束。

我已经在线查看,根据我发现以下代码应该可以工作但是我得到并且错误并且它不喜欢细胞系(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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

根据你的叙述("我必须......删除一个行")你似乎只打扰了一次短语" CFS-GHOST-DJKT& #34;

在这种情况下,不需要迭代单元格,只需尝试找到它,如果成功,则删除整行

    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