Macro to merge cells in a column if the same rows are merged in a different column

2

1

I need help finding a macro that can merge cells across rows in a column if those same rows are already merged in another column. Below is a screenshot of what I have now that shows the cells that are merged in Column A.

before

The below screenshot is what I need the spreadsheet to look like after the macro runs; the corresponding cells in Column B are merged.

after

NPatel

Posted 2013-06-25T20:28:44.787

Reputation: 23

Welcome to superuser, as always: What have you tried so far? Do you have some VBA code with an actual problem where you stuck? – nixda – 2013-06-25T20:44:10.447

No VBA now just because I don't have too much experience with writing VBA. I have tried to solve with using the CONCATENATE function in column B referencing the cells in column A with the criteria of being merged, but so far have been unsuccessful. I searched related posts on Superuser for macros to potentially solve this, but have not been able to find macros that merge cells referencing other merged cells. – NPatel – 2013-06-25T21:24:24.027

Answers

1

This was the shortest I could make. I tried it with your example and it worked for me.

Sub mergecolumn()

Dim cnt As Integer
Dim rng As Range
Dim str As String

For i = ActiveSheet.UsedRange.Rows.Count To 1 Step -1
    cnt = Cells(i, 1).MergeArea.Count
    Set rng = Range(Cells(i, 2), Cells(i - cnt + 1, 2))

    For Each cl In rng
        If Not IsEmpty(cl) Then str = str + vbNewLine + cl
    Next
    If str <> "" Then str = Right(str, Len(str) - 2)

    Application.DisplayAlerts = False
    rng.Merge
    rng = str
    Application.DisplayAlerts = True

    str = ""
    i = i - cnt + 1
Next i

End Sub

nixda

Posted 2013-06-25T20:28:44.787

Reputation: 23 233

Once I knew a better/shorter way to concatenate cells. It was something with join, split, array and range. Dammit, I forgot it. – nixda – 2013-06-25T22:31:44.177

Thanks so much! The VB worked perfectly. Thanks again for your help! – NPatel – 2013-06-25T22:38:26.260