How do I ignore the first row in an Excel macro that deletes all rows based on a criteria?

后端 未结 3 1164
终归单人心
终归单人心 2020-12-02 02:54

This macro is designed to compare the data in column C and D and if C does not match D in a certain row, it deletes the entire tow. The problem is that it deletes the header

3条回答
  •  醉梦人生
    2020-12-02 03:33

    Deletion of a row is an operation that takes quite some time. Thus, it is a good idea to make all deletions at once, uniting all rows to be deleted in a specific range wholeRange:

    Option Explicit
    
    Public Sub DeleteNonMatchingRows()
    
        Dim LastRow As Long
        LastRow = Cells(Rows.Count, "C").End(xlUp).Row
    
        Dim wholeRange  As Range
        Dim iRow As Long
        For iRow = LastRow To 2 Step -1
            If Range("C" & iRow) <> Range("D" & iRow) Then
                If wholeRange Is Nothing Then
                    Set wholeRange = Rows(iRow)
                Else
                    Set wholeRange = Union(wholeRange, Rows(iRow))
                End If
            End If
        Next iRow
    
        If Not wholeRange Is Nothing Then
            wholeRange.Select       'delete this row
            Stop                    'delete this row
            wholeRange.Delete
        End If
    
    End Sub
    

    Once you run the code, it will stop on the Stop line. You will be able to see the range, which is to be deleted. The range will be selected. Once you see it, it is a good idea to delete the two rows, mentioned in the comments, you are not going to need them any more.

提交回复
热议问题