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

后端 未结 3 1169
终归单人心
终归单人心 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:38

    If you use a descriptive variable naming, eg. rename i into iRow you will never forget that this is your row counter, that is counting from row 9999 to row 1 in For iRow = 9999 To 1 Step -1. So you need to change the 1 into a 2 to omit the first row.

    I recommend to use a dynamic start for your loop that automatically finds the last used row. This prevents unnecessary loop steps and you don't need to increase it for larger worksheets.

    Option Explicit
    
    Public Sub DeleteNonMatchingRows()
        Dim LastRow As Long
        LastRow = Cells(Rows.Count, "C").End(xlUp).Row 'find last used row in column C
    
        Dim iRow As Long
        For iRow = LastRow To 2 Step -1 
            If Range("C" & iRow) <> Range("D" & iRow) Then
                'Range("C" & iRow).EntireRow.Delete
                 Rows(iRow).Delete 'directy delete a row
            End If
        Next iRow
    End Sub
    

提交回复
热议问题