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

≡放荡痞女 提交于 2020-01-06 21:10:52

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/30308002/how-do-i-get-all-the-different-unique-combinations-of-3-columns-using-vba-in-exc

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