在 excel 中找到所有可能的组合

Find all possible combination in excel

我有excel这样的数据

X    Y

a    1
b    2 
c    3

我想在 X 列中进行所有可能的组合,并从 Y 列中生成总和

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

此示例立即生成输出 window。根据您的输出需求进行调整。

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

所以这个……

将输出……

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