首页 > 解决方案 > 在给定条件下使用 VBA 同时删除两行

问题描述

条件是Column A,如果单元格( A1,A2,A3....)是合并单元格,则删除整行和该单元格上方的行

我知道如何删除一整行,但是在尝试删除第二行时我复制了语言(我可以把它们放在一起吗?)

Sub test()

Dim i As Integer

For i = 1 To 300 Step 1
    If Cells(i, 1).MergeCells = True Then
        Rows(i - 1).EntireRow.Delete 'delete  the row above the merged cell
    End If
Next i

For i = 1 To 300 Step 1
    If Cells(i, 1).MergeCells = True Then
    Rows(i).EntireRow.Delete 'delete another row where the merged cell is
    End If
Next i

End Sub

标签: vbaexcel

解决方案


你可以试试这个:

Sub test()
    Dim i As Long

    For i = 300 To 1 Step -1
        If Cells(i + 1, 1).MergeCells Then Rows(i).Resize(2).EntireRow.Delete 'delete the row with the merged cell and the row above
    Next
    If Cells(1, 1).MergeCells Then Rows(1).EntireRow.Delete 'if first cell is merged, then delete its row
End Sub

推荐阅读