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

时间:2019-01-09 09:37:44

标签: excel vba excel-formula excel-2010 excel-2007

我有这样的excel数据

X    Y

a    1
b    2 
c    3

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

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

1 个答案:

答案 0 :(得分:0)

此示例在立即窗口中产生输出。根据您的输出需求进行调整。

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

所以这个…
enter image description here

将输出...

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