简体   繁体   中英

Excel - Delete current row and row above based on cell value

Each week I receive a spreadsheet that can contain up to 4,000 rows. If any date is in Column C, I need to delete that row and the row above it. Can someone help me with some VBA code that I can run on each new file which I get each week. It's a pain to go through 4,000+ rows of data by hand each week.

In the screenshot, I would be deleting rows 157, 158, 159 and 160.
屏幕截图显示了要删除的行

Much appreciate the help.

Give this short macro a try:

Sub dural()
    Dim N As Long, i As Long, v As Variant

    N = Cells(Rows.Count, "C").End(xlUp).Row

    For i = N To 2 Step -1
        v = Cells(i, "C").Value
        If v <> "" Then
            If IsDate(v) Then
                Range(Cells(i, "C"), Cells(i - 1, "C")).EntireRow.Delete
            End If
        End If
    Next i
End Sub

EDIT#1:

If you have two or more sequential cells with dates like:

在此处输入图片说明

then this code should be used:

Sub dural()
    Dim N As Long, i As Long, v As Variant
    Dim rKill As Range
    N = Cells(Rows.Count, "C").End(xlUp).Row
    Set rKill = Nothing
    For i = N To 2 Step -1
        v = Cells(i, "C").Value
        If v <> "" Then
            If IsDate(v) Then
                If rKill Is Nothing Then
                    Set rKill = Cells(i, "C")
                    Set rKill = Union(rKill, Cells(i - 1, "C"))
                Else
                    Set rKill = Union(rKill, Cells(i, "C"))
                    Set rKill = Union(rKill, Cells(i - 1, "C"))
                End If
            End If
        End If
    Next i

    If rKill Is Nothing Then Exit Sub
    rKill.EntireRow.Delete
End Sub

(this will insure that all the "x" rows also get deleted.)

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