Link to home
Start Free TrialLog in
Avatar of Murray Brown
Murray BrownFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Excel VBA Merge Cells

Hi

What Excel VBA would I use to do each of the ollowing Excel merges

Merge & Center
Merge Across
Merge Cells
Avatar of Ingeborg Hawighorst (Microsoft MVP / EE MVE)
Ingeborg Hawighorst (Microsoft MVP / EE MVE)
Flag of New Zealand image

Hello,

to find out about commands like these, fire up the macro recorder and use the commands one after the other. Then stop the macro recorder and see the code:

Option Explicit

Sub Macro1()
'
' Macro1 Macro
'

'
    Range("A1:C1").Select
    With Selection
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Selection.Merge
    Range("A2:C2").Select
    Selection.Merge True
    Range("A3:C3").Select
    Selection.Merge
    Range("A1:C3").Select
    Selection.UnMerge
End Sub

Open in new window


The macro recorder always uses the Select statement, which you can trim from your final code, like

Sub Macro1()

'Merge and Center
    With Range("A1:C1")
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlBottom
        .WrapText = False
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    Range("A1:C1").Merge
    
' Merge across
    Range("A2:C2").Merge True

' Merge
    Range("A3:C3").Merge

' Unmerge
    Range("A1:C3").UnMerge
End Sub

Open in new window


cheers, teylyn
Avatar of Murray Brown

ASKER

Hi. Thanks

I had done that and post the question because step 1 and 3 seem to be exactly the same,
ASKER CERTIFIED SOLUTION
Avatar of Ingeborg Hawighorst (Microsoft MVP / EE MVE)
Ingeborg Hawighorst (Microsoft MVP / EE MVE)
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I see. I had assumed that that first bit would have happened for all the merge types but woke up this morning realising that it might not, so thanks very much for the clarification...