选择具有合并单元格的行并将其删除(行)

时间:2018-12-18 15:33:31

标签: excel vba excel-vba

Google搜索,我发现了一个突出显示活动工作表中合并单元格的过程:

Sub DeleteRows()
    Dim x As Range
    For Each x In ActiveSheet.UsedRange
        If x.MergeCells Then
            x.Interior.ColorIndex = 8
            ActiveCell.EntireRow.Delete
        End If
    Next
End Sub

因此,我添加了ActiveCell.EntireRow.Delete语句以删除当前迭代的行。

我要去哪里错了?

我不太在乎突出显示合并的单元格。最终目标是删除其中具有合并单元格的任何行。

3 个答案:

答案 0 :(得分:5)

找出所有合并的单元格范围,将它们合并并一口气删除。


Sub DeleteRows()
        Dim x           As Range
        Dim rngDelete   As Range

        For Each x In ActiveSheet.UsedRange
            If x.MergeCells Then

                If rngDelete Is Nothing Then
                    Set rngDelete = x
                Else
                    Set rngDelete = Union(rngDelete, x)
                End If

            End If
        Next

        If Not rngDelete Is Nothing Then
            rngDelete.EntireRow.Delete
        End If


    End Sub

答案 1 :(得分:1)

删除行时,请始终从下往上删除,或者a)冒着删除要检查的下一个单元格的风险,并且b)冒着跳过出现的行来代替已删除行的风险。

Sub DeleteRows()
    Dim r as long, c as long

    with ActiveSheet.UsedRange
        'work backwards through the rows
        For r = .rows.count to 1 step -1
            'work forwards through the columns
            For c = 1 to .columns.count
                If .cells(r, c).MergeCells Then
                    'once a merged cell is found, delete then go immediately to the next row
                    .cells(r, c).EntireRow.Delete
                    exit for
                End If
            next c
        Next r
    end with

End Sub

答案 2 :(得分:0)

一种快速的方法是找到所有合并的单元格,然后一次性删除它们:一种好方法是使用范围。使用合并后的单元格“格式”查找然后合并找到的范围< / p>

  

以下代码循环遍历合并范围并创建并集,然后选择整个行

Sub SelectMerge()
    Dim rng As Range, rngUnion As Range, Test As Range
    Dim ws As Worksheet: Set ws = ActiveSheet

    With Application.FindFormat
        .Clear
        .MergeCells = True
    End With

    With ws.UsedRange
        Set rng = .Find("", SearchFormat:=True)
        Do
            If Not rngUnion Is Nothing Then Set rngUnion = Application.Union(rng, rngUnion)
            If rngUnion Is Nothing Then Set rngUnion = rng
            If rng Is Nothing Then Exit Do
            Set rng = .Find("", After:=rng, SearchFormat:=True)
        Loop While Application.Intersect(rng, rngUnion) Is Nothing
    End With
    If Not rngUnion Is Nothing Then rngUnion.EntireRow.Select 'rngUnion.EntireRow.Delete

End Sub