VBA: Merge cells based on values in a specific column

zzzz02

New Member
Joined
Dec 2, 2023
Messages
3
Office Version
  1. 2019
Platform
  1. Windows
Hi everyone, I am a student who's new to Excel VBA and need some help with my code
I have a column of values in range L4:L53:
4
2
2
2
2
3
5
.... and so on

What I wish to do is merge the cells starting from X4 according to the values in column L
E.g. The value in L4 is 4, cells X4:X7 should merge together
The value in L5 is 2, cells X8:X9 should merge together
The value in L6 is 2, cells X10:X11 should merge together and so on.

Is there a VBA code that can achieve this, or do I need to do this manually? I appreciate your help!!
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
VBA Code:
Sub For_zz()
    m = 4
    For i = 4 To 53
        Range(Cells(m, 24), Cells(m + Cells(i, 12).Value - 1, 24)).Merge
        m = m + Cells(i, 12).Value
    Next
End Sub
 
Upvote 1
Solution
VBA Code:
Option Explicit

Sub MergeCells()
Dim wb As Workbook, sht As Worksheet, dRng As Range, sRng As Range, cell As Range
Set wb = ThisWorkbook: Set sht = wb.Sheets(1): Set dRng = sht.Range("L4:L53")
Set sRng = sht.Range("X4")
For Each cell In dRng
    sht.Range(sRng, sRng.Offset(cell.Value, 0)).Merge
    Set sRng = sRng.Offset(1, 0)
Next cell
End Sub
 
Upvote 0
VBA Code:
Option Explicit

Sub MergeCells()
Dim wb As Workbook, sht As Worksheet, dRng As Range, sRng As Range, cell As Range
Set wb = ThisWorkbook: Set sht = wb.Sheets(1): Set dRng = sht.Range("L4:L53")
Set sRng = sht.Range("X4")
For Each cell In dRng
    sht.Range(sRng, sRng.Offset(cell.Value, 0)).Merge
    Set sRng = sRng.Offset(1, 0)
Next cell
End Sub
thank you!!
 
Upvote 0

Forum statistics

Threads
1,223,886
Messages
6,175,193
Members
452,616
Latest member
intern444

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top