Search code examples
excelvbaexcel-formulaexcel-2010excel-2007

Find all possible combination in excel


I have excel data like this

X    Y

a    1
b    2 
c    3

I want to do all possible combination in Column X, and generating sum from column Y

a+b    3
a+c    4
a+b+c  6
b+c    5

Solution

  • This example produces the output in the immediate window. Adjust it to your output needs.

    Option Explicit
    
    Public Sub Combine()
        Dim ws As Worksheet
        Set ws = ThisWorkbook.Worksheets("Sheet1")
    
        Dim LastRow As Long
        LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    
        Dim iRow As Long, jRow As Long, kRow As Long
        For iRow = 2 To LastRow
            For jRow = iRow + 1 To LastRow
    
                'output 2-combos
                Debug.Print ws.Cells(iRow, "A").Value & "+" & ws.Cells(jRow, "A").Value, ws.Cells(iRow, "B").Value + ws.Cells(jRow, "B").Value
    
                For kRow = jRow + 1 To LastRow
                    'output 3-combos
                    Debug.Print ws.Cells(iRow, "A").Value & "+" & ws.Cells(jRow, "A").Value & "+" & ws.Cells(kRow, "A").Value, ws.Cells(iRow, "B").Value + ws.Cells(jRow, "B").Value + ws.Cells(kRow, "B").Value
                Next kRow
            Next jRow
        Next iRow
    End Sub
    

    So this …
    enter image description here

    will output …

    a+b            3 
    a+b+c          6 
    a+b+d          7 
    a+c            4 
    a+c+d          8 
    a+d            5 
    b+c            5 
    b+c+d          9 
    b+d            6 
    c+d            7