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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

StephenJRCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.