删除连续的行 EXCEL VBA

Delete consecutive ROWs EXCEL VBA

我的数据在 A 列中,我想删除 B 列中的所有连续行。 代码

  If Range("A" & i).Value = Range("A" & i).Offset(1, 0).Value Then
    Rows(i & ":" & i).Delete shift:=xlUp
  End If

我写了脚本,但我不知道如何把它放在一个循环中..任何帮助谢谢。

通常,删除行的最佳方式是从底部开始并向顶部移动。这避免了 'skipping' 删除行时行向上移动。

Dim rw As Long

With Sheets("Sheet1")
    For rw = .Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
        If .Cells(rw, 1).Value = .Cells(rw - 1, 1).Value Then _
            .Rows(rw).Delete
    Next rw
End With

同样,通常一列数据会有一个列 header 标签,您不希望在删除过程中涉及该标签。但是,只要标签(如果有的话)与第 2 行中的单元格值不匹配,这应该不是问题。

由于删除行非常耗时,因此此任务的最佳方法是使用 [=12= 将所有要删除的行收集到 Range class 的单个对象中] 函数,然后一次操作将它们全部删除。

下面是介绍如何做到这一点的代码:

Sub deleteConsecutiveRows()
    Dim wks As Excel.Worksheet
    Dim rng As Excel.Range
    Dim row As Long
    Dim lastRow As Long
    '-------------------------------------------------------------------------


    Set wks = Excel.ActiveSheet


    With wks
        lastRow = .Cells(.Rows.Count, 1).End(xlUp).row

        For row = 2 To lastRow
            If .Cells(row, 1).Value = .Cells(row - 1, 1).Value Then

                If rng Is Nothing Then
                    Set rng = .Rows(row)
                Else
                    Set rng = Excel.Union(rng, .Rows(row))
                End If

            End If
        Next row

    End With


    'In order to avoid Run-time error check if [rng] range is not empty, before removing it.
    If Not rng Is Nothing Then
        Call rng.EntireRow.Delete
    End If


End Sub