如何使用 Excel 中的 VBA 获得两列的所有不同唯一组合并对第三列求和

How do I get all the different unique combinations of 2 columns using VBA in Excel and sum the third

这是

的后续

这几乎是我所需要的,但是,我的要求是它对第三列求和,该列将包含数字而不是 yes/no

Sub sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long, j As Long
Dim col As New Collection
Dim Itm
Dim cField As String

Const deLim As String = "#"

Set ws = ThisWorkbook.Sheets("Sheet1")

With ws
    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    For i = 2 To lRow
        cField = .Range("A" & i).Value & deLim & _
                 .Range("B" & i).Value & deLim & _
                 .Range("C" & i).Value

        On Error Resume Next
        col.Add cField, CStr(cField)
        On Error GoTo 0
    Next i

    i = 2

    .Range("A1:C1").Copy .Range("F1")
    .Range("I1").Value = "Count"

    For Each Itm In col
        .Range("F" & i).Value = Split(Itm, deLim)(0)
        .Range("G" & i).Value = Split(Itm, deLim)(1)
        .Range("H" & i).Value = Split(Itm, deLim)(2)


        For j = 2 To lRow
            cField = .Range("A" & j).Value & deLim & _
                     .Range("B" & j).Value & deLim & _
                     .Range("C" & j).Value

            If Itm = cField Then nCount = nCount + 1
        Next
        .Range("I" & i).Value = nCount

        i = i + 1
        nCount = 0
    Next Itm
End With

结束子

此代码最初由

添加

悉达多溃败

试试这个(关注评论)

Option Explicit

Sub Main()
    Dim i As Long
    Dim dict As Object

    Set dict = CreateObject("Scripting.Dictionary")
    For i = 4 To Range("A" & Rows.Count).End(xlUp).Row '<-- change 4 and "A" to your data actual upleftmost cell row and column
        dict(cells(i, 1).Value & "|" & cells(i, 2).Value) = dict(cells(i, 1).Value & "|" & cells(i, 2).Value) + cells(i, 3).Value '<--| change 3 to your actual "column to sum up" index
    Next

    With Range("G3").Resize(dict.Count) '<-- change "G3" to your actual upleftmost cell to start writing output data from
        .Value = Application.Transpose(dict.Keys)
        .TextToColumns Destination:=.cells, DataType:=xlDelimited, Other:=True, OtherChar:="|"
        .Offset(, 2).Resize(dict.Count).Value = Application.Transpose(dict.Items) '<--| change 2 to your actual column offset where to start writing summed values form
    End With
End Sub