Macro to merge and concatenate cells in Excel for rows in which information on other columns matches

心不动则不痛 提交于 2020-01-17 11:14:12

问题


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


回答1:


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



回答2:


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...



来源:https://stackoverflow.com/questions/28958879/macro-to-merge-and-concatenate-cells-in-excel-for-rows-in-which-information-on-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!