简体   繁体   中英

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

I run a report weekly and a step I must take is to delete a row that contains a certain phrase, in my case "CFS-GHOST-DJKT", in column A. Rows to read through start at 7 and have a variable end.

I have looked online and according to what I have found the following code should work but I get and error and it does not like the line With Cells(Lrow,"A")

I believe as far as the deleteing part goes it is ok the way it is written but the problem is the selection aspect.

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

You need to iterate from the last row to the first row when deleting else you will end up skipping rows.

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

as per you narrative ("I must ... delete a row") you seem to bother only one occurrence of the phrase "CFS-GHOST-DJKT"

in this case there's no need for iterating through cells but just try finding it and, if successful, delete its entire row

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM