如何忽略Excel宏中根据条件删除所有行的第一行?

时间:2018-05-15 12:19:38

标签: excel vba excel-vba

此宏用于比较C列和D列中的数据,如果C与某行中的D不匹配,则删除整个拖曳。问题是它删除了Excel表格第1行中的标题,因为它们不匹配。如何为第2行到第9999行而不是所有9999行运行宏。

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

3 个答案:

答案 0 :(得分:4)

删除行是一项需要相当长时间的操作。因此,最好一次进行所有删除,将所有行组合在特定范围内删除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

运行代码后,它将停在Stop行。您将能够看到要删除的范围。范围将被选中。一旦你看到它,最好删除评论中提到的两行,你不再需要它们了。

答案 1 :(得分:3)

如果使用描述性变量命名,例如。将i重命名为iRow,您永远不会忘记这是您的行计数器,即9999中的行1到行For iRow = 9999 To 1 Step -1。因此,您需要将1更改为2以省略第一行。

我建议为循环使用动态启动,自动查找最后使用的行。这可以防止不必要的循环步骤,并且您无需为更大的工作表增加它。

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

答案 2 :(得分:0)

你可以避免循环:

Sub deleteNonMatchingRows()
    With Range("C2", Cells(Rows.Count, "C").End(xlUp)) ' reference column C cells from row 2 doen to last not empty one
        With .Offset(, .Parent.UsedRange.Columns.Count) ' reference referenced range offset by active sheet used range columnns (to be sure you'r not overwriting already filled cells)
            .FormulaR1C1 = "=IF(RC3<>RC4,1,"""")" ' have referenced cells show a "1" if corresponding cells in column C and D match
            .SpecialCells(xlCellTypeFormulas, xlNumbers).EntireRow.Delete ' delete all rows whose referenced column formula result is a number
            .ClearContents ' clear referenced range
        End With
    End With
End Sub