1
votes

apologize if this is a common post, but couldn't find something that fully applies to me.

It's a very similar post to (except that instead of just merging the 2 cells, i am looking to merge and concatenate): Macro to merge cells in Excel for rows in which information in other columns matches

Referencing the image in the post above, what i am looking for are cells P2 and P3 to be merged and the data to be concatenated. For eg: if P2 had abc, and P3 had xyz, i am looking for end product to be abcxyz in the merged cell.

Any help would be greatly appreciated. What i have only enables me to merge, but i am not sure how to concatenate it.

Sub Main()

Dim i As Long
Dim j As Long

Dim sameRows As Boolean
sameRows = True

For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
    For j = 1 To 6
        If StrComp(Cells(i, j), Cells(i + 1, j), vbTextCompare) Then
            sameRows = False
        End If
    Next j

    If sameRows Then
        Range(Cells(i, 7), Cells(i + 1, 7)).Merge
    End If

    sameRows = True
Next i

End Sub

2
Feel free to mark my answer as your solution if it helped youKᴀτᴢ

2 Answers

0
votes

simply add this line in the code:

Cells(i, 7).Value = Cells(i, 16).Text + Cells(i + 1, 16).Text

complete code:

Sub merge()
Dim i As Long
Dim j As Long

Dim sameRows As Boolean
sameRows = True

For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
    For j = 1 To 6
        If StrComp(Cells(i, j), Cells(i + 1, j), vbTextCompare) Then
            sameRows = False
        End If
    Next j

    If sameRows Then
        Range(Cells(i, 7), Cells(i + 1, 7)).merge
        Cells(i, 7).Value = Cells(i, 16).Text + Cells(i + 1, 16).Text
    End If

    sameRows = True
Next i
End Sub
0
votes

The solution is pretty straightforward: you store the first String inside a variable,

Dim FinalText As String

FinalText = Cells(i, 7).Text

add the second String

FinalText = FinalText & Cells(i + 1, 7).Text

then after merging the two cells, you write the content of the variable in your merged cell.

Cells(i, 7) = FinalText

I'm not going to give you the full solution though, since you copy-pasted what you found and wouldn't try to write something by yourself.

EDIT: if more than one cell is to be merged, I'd use the same technique, but using FinalText = FinalText & Cells(i + 1, 7).Text inside the condition that checks if the values contained in each cell is equal...