Can anyone help me write a vba code to merge same value cells in different columns as shown below.
I have tried using the code below but doesn't work;
Sub mergeWeeks()
Dim lc As Long, nc As Long, cr As Long, rng As Range
Application.DisplayAlerts = False
With Worksheets("sheet2")
For cr = 1 To 2
lc = Application.Match("zzz", .Rows(cr))
Set rng = .Cells(cr, 1)
Do While rng.Column < lc
nc = Application.Match(rng.Value & "z", .Rows(cr))
rng.Resize(1, nc - rng.Column + 1).Merge
Set rng = rng.Offset(0, 1)
Loop
Next cr
End With
Application.DisplayAlerts = True
End Sub
Merge in Rows
Links
Workbook Download: "how-do-you-merge-same-value-columns-using-vba_54279695.xls"
Another 3D Array Example on SO: Array of Arrays feat. 3-dimensional Jagged Arrays
Features
cSheet
) can be entered as name or index.cRows
). TheTrim
function insures correct functionality even if there are (accidental) spaces between commas and row numbers.cFirstC
) while the last column (LastC
) is being calculated in the first row.rngU
) in MERGE and the 3D array of arrays (vntAA
) in UNMERGE should ensure great efficiency.Merge Union Version
UnMerge 3D Array Version
merge cells horizontally, when value identical
merge cells horizontally, when month identical
If it's enough to compare the values (e. g. each "jan" is just the same string), then the code above works.
If the month is based on a cell format of different dates (e. g. dec 1st, dec 8th, dec 15th ... all shown as "dec" or "12"), then you can compare
Month(rng.Value)
withMonth(rng.Offset(0, -1).Value)
.Unmerge
As
Range.Find
is bad in finding the last used column, if it's within merged cells. So I use the standardUsedRange
instead to find it even when cells are merged.Using Range.Find with xlPrevious should wrap around the worksheet row to find the last occurrence of a value.