Thank you iliace, great code!
Before I try it out, I wonder if the unmerge is also done automatically when the code runs (to unmerge previously merged cells/rows within the range). Do we need an extra "unmerge" subroutine ahead?
Can this macro code be run automatically if the cell content changes?
What I try to do, combined with conditional formating, is:
1. The main range I want to run "merge" take values from a shadow identical range (outside the visible page). That gives cells a specific format with conditional formating. I want to keep the main range readonly, so the editors only change data in the shadow range (actually the source is linked to an editable sheet, separate).
2. Then, in the main range I want to merge the adiacent cells only (columns and rows) that have identical values (Not Null) - mostly text, but your code is already doing that for numbers so no problem.
3. When the editable range has cells with updated values (either emptied or text changed), I want the Main Range to be unmerged, then consecutively remerged based on the new content.
Of course, the colors and other formats will also update, automatically based on the new values in the shadew range.
It would be great if it would work automatically on cell update, but also a manual button could work (if there is a limitation in the first case).
The final code you provided was this:
Code:
[LIST=1]
[*]Public Sub mergeSameCell()
[*] Dim rng As Excel.Range, rngPrev As Excel.Range
[*] Dim rngAll As Excel.Range, rngMerge As Excel.Range
[*] Dim rngBegin As Excel.Range, rngEnd As Excel.Range
[*] If VBA.TypeName(Selection) <> "Range" Then Exit Sub
[*] Set rngAll = Application.Selection
[*] Application.Calculation = Excel.xlCalculationManual
[*] Application.ScreenUpdating = False
[*] For Each rng In rngAll.Cells
[*] If rngBegin Is Nothing Then
[*] Set rngBegin = rng
[*] ElseIf rng.Value <> rngPrev.Value Or rng.Row <> rngPrev.Row Then
[*] If (VBA.Len(rngPrev.Value) > 0) Then
[*] Set rngEnd = rngPrev
[*] Set rngMerge = Range(rngBegin, rngEnd)
[*] If rngMerge.Cells.Count > 1 Then
[*] Application.DisplayAlerts = False
[*] rngMerge.Merge
[*] Application.DisplayAlerts = True
[*] End If
[*] End If
[*] Set rngBegin = rng
[*] End If
[*] Set rngPrev = rng
[*] Next rng
[*] Set rngEnd = rngAll.Cells(rngAll.Cells.Count)
[*] Set rngMerge = Range(rngBegin, rngEnd)
[*] If rngMerge.Cells.Count > 1 Then
[*] Application.DisplayAlerts = False
[*] rngMerge.Merge
[*] Application.DisplayAlerts = True
[*] End If
[*] Application.Calculation = Excel.xlCalculationAutomatic
[*] Application.ScreenUpdating = True
[*]End Sub
[/LIST]
Can you adjust it for my needs please? I really apreciate it!