excel - 删除连续的ROWs EXCEL VBA

标签 excel vba loops rows

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

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

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

enter image description here

最佳答案

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

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

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

关于excel - 删除连续的ROWs EXCEL VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31606080/

相关文章:

函数声明中的 VBA 可空类型

excel - 使用 Excel-VBA 更新用户表单的按钮

R - 通过循环遍历向量中的元素将列添加到列表中的数据帧

c# - 从字符串创建对象名称

arrays - 数组 VBA 中的用户定义对象

arrays - ARRAY公式EXCEL中的多条件IF语句

excel - 将字符串保存到 VBA 中未初始化的 Variant 变量中

vba - 根据单元格内容选择 Excel 中的单元格

vba - 如何使用vba获取powerpoint幻灯片尺寸?

Python 循环没有给出预期的输出