How do I create an Excel macro that will delete rows containing merged cells?

Hi,

I am trying to create an Excel macro that will search all rows in a spreadsheet, and if the rows contain merged cells, delete them.  I am using the following code...I don't get any error messages, but rows containing merged cells are not deleted.  Any help is appreciated!

Thanks,

mvem
Sub test()

Dim lastrow As Long

lastrow = ActiveSheet.UsedRange.Rows.Count

For r = 1 To lastrow Step 1

    If Rows(r).MergeCells = True Then
    Rows(r).Delete
    End If

Next r

End Sub

Open in new window

mvemAsked:
Who is Participating?
 
StephenJRConnect With a Mentor Commented:
Here is one possible approach.
Sub test()

Dim rng As Range

For Each rng In ActiveSheet.UsedRange
    If rng.MergeCells = True Then
        rng.EntireRow.Delete
    End If
Next rng

End Sub

Open in new window

0
 
patrickabCommented:
mvem,

You can use either of the subs below.

Patrick
Sub test()
Dim lastrow As Long
Dim r As Long

lastrow = ActiveSheet.UsedRange.Rows.Count

For r = lastrow To 1 Step -1
    If Rows(r).MergeCells = True Then
        Rows(r).Delete
    End If
Next r

End Sub

Sub test2()
Dim celle As Range

For Each celle In ActiveSheet.UsedRange
    If celle.MergeCells = True Then
        Rows(celle.Row).Delete
    End If
Next celle
End Sub

Open in new window

0
 
patrickabCommented:
xover...
0
 
telyni19Commented:
I think Rows(r).MergeCells tests whether the whole row is merged, which it probably won't be. Try the below instead.
Sub test()
Dim tempcell As Range
For Each tempcell In ActiveSheet.UsedRange
        If tempcell.MergeCells Then tempcell.EntireRow.Delete
Next tempCell
End Sub

Open in new window

0
 
telyni19Commented:
Sorry, I don't think my solution is anything new either. The thread was blank when I started typing.
0
All Courses

From novice to tech pro — start learning today.