简体   繁体   中英

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

This is a follow on from How do I get all the different unique combinations of 3 columns using VBA in Excel?

It almost what i need, however, my requirements is that it sums the third column which will contain figures instead of 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

End Sub

This code was originally added by

Siddharth Rout

try this (follows comments)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM