Combine Rows with duplicate values, merge cells if different

后端 未结 3 1064
生来不讨喜
生来不讨喜 2020-12-07 03:35

I have similar question to [combine Rows with Duplicate Values][1] Excel VBA - Combine rows with duplicate values in one cell and merge values in other cell

I have

3条回答
  •  粉色の甜心
    2020-12-07 04:25

    variant using dictionary below

    Sub test()
        Dim Dic As Object: Set Dic = CreateObject("Scripting.Dictionary")
        Dic.Comparemode = vbTextCompare
        Dim Cl As Range, x$, y$, i&, Key As Variant
        For Each Cl In Range("B2:B" & Cells(Rows.Count, "B").End(xlUp).Row)
            x = Cl.Value & "|" & Cl.Offset(, 1).Value
            y = Cl.Offset(, 2).Value
            If Not Dic.exists(x) Then
                Dic.Add x, Cl.Offset(, -1).Value & "|" & y & "|"
            ElseIf Dic.exists(x) And Not LCase(Dic(x)) Like "*|" & LCase(y) & "|*" Then
                Dic(x) = Dic(x) & "|" & y & "|"
            End If
        Next Cl
        Range("A2:D" & Cells(Rows.Count, "B").End(xlUp).Row).ClearContents
        i = 2
        For Each Key In Dic
            Cells(i, "A") = Split(Dic(Key), "|")(0)
            Range(Cells(i, "B"), Cells(i, "C")) = Split(Key, "|")
            Cells(i, "D") = Replace(Split(Replace(Dic(Key), "||", ";"), "|")(1), ":", ";")
            i = i + 1
        Next Key
        Set Dic = Nothing
    End Sub
    

    before

    enter image description here

    after

    enter image description here

提交回复
热议问题