Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

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

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 headers in Row 1 on the Excel sheet because they don't match. How do I run the macro for rows 2 through 9999 instead of all 9999 rows.

Sub deleteNonMatchingRows()
    Dim i As Long

    For i = 9999 To 1 Step -1 ' it will scan 9999 rows of the sheet. This number can be increased for larger sheets
        If Range("C" & i) <> Range("D" & i) Then
            Range("C" & i).EntireRow.Delete
        End If
    Next
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...