Excel VBA, Merge Cells

In this article I will explain how you can use VBA to merge cells in Excel. I have also provided two sample codes.

Jump To:

You can download the code and file related to this article here.


Contents

Basics, MergeCells:

Using the code below the cells A1 to D1 will be merged:

Range("A1:D1").MergeCells = True

Before:

Excel VBA, Merge Cells Before

After:

Excel VBA, Merge Cells After
The line below will remove the merge cell property from the cells A1 to D1:

Range("A1").MergeCells = False

Note the lines below will not remove the merge cell property:

Range("A2").MergeCells = False

Range("A3").MergeCells = False

Range("A4").MergeCells = False


Example 1, Merge Rows:

The code below will loop through the rows in column A and merge the first 3 cells in each row:

Sub Exampl1()
Dim i As Integer
For i = 1 To 10
    Range(Cells(i, 1), Cells(i, 3)).MergeCells = True
Next i
End Sub

Before:

Excel VBA, Merge Rows
After:

Excel VBA, Merge Rows After


Example 2, Merge Columns:

The code below will loop through the first 8 columns in row 1 and merge the first 7 cells in each column:

Sub Example2()
Dim i As Integer
For i = 1 To 8
    Range(Cells(1, i), Cells(7, i)).MergeCells = True
Next i
End Sub

Before:

VBA Merge Cell Before

After:

VBA Merge Cell After

You can download the code and file related to this article here.

See also:

If you need assistance with your code, or you are looking for a VBA programmer to hire feel free to contact me. Also please visit my website  www.software-solutions-online.com

Leave a Reply

Your email address will not be published. Required fields are marked *