如何修改Excel条件删行宏,使其忽略首行仅处理第2至9999行?
Got it, the problem here is that your macro starts checking all the way at row 1—your header row! Since the header text in columns C and D don’t match, it gets caught in the deletion logic and gets erased. The fix is really straightforward: we just need to adjust the starting point of your loop to start at row 2 instead of row 1.
Also, quick kudos for looping from the bottom up (9999 down to your starting row)! This is the right approach because if you looped top to bottom, deleting a row would shift all the rows below it upward, and your macro would end up skipping some rows without ever checking them.
Here’s the modified code that skips the header row:
Sub deleteNonMatchingRows() Dim i As Long ' Start at row 9999 and loop down to row 2 to preserve the header For i = 9999 To 2 Step -1 ' Check if columns C and D have mismatched values If Range("C" & i) <> Range("D" & i) Then Range("C" & i).EntireRow.Delete End If Next i End Sub
A quick note: if your sheet ever grows beyond 9999 rows, just update that number to match your maximum row count to make sure all data rows are checked.
内容的提问来源于stack exchange,提问作者Bryan

