简体   繁体   中英

How do I get all the different unique combinations of 3 columns using VBA in Excel?

I have an Excel worksheet with several columns, where 3 of them form a "unique key".
If I have fruits in column A (Apple, Banana, Orange), some name in column B (John, Peter) and something like Yes/No in column C, I want to be able to get sums of values from rows where the values in these columns are the same. For instance, the sum of all the values in column D for rows where columns A, B and C are Apple,John,Yes.

Sorry for the confusing text, but I don't know how to express my question more clearly. I've never done anything in VBA so I'm a bit lost here...

Here's an example of the expected result. 预期结果

It is also possible to go to the data tab -> remove duplicates. You can then select which columns you would like to compare in removing the dulicates.

I don't know in advance which combinations exist. The goal is to list all the unique combinations and the sum of some other columns. Can I do this without using VBA?

No Formulas/VBA required. Use a Pivot table for a summary of all combinations. See screenshot

在此处输入图片说明

If you still want VBA then that can also be done :)

EDIT

I quickly wrote this

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

在此处输入图片说明

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