我想知道Excel中是否有功能或功能组合(可能需要VBA),这有助于我解决以下问题:
该组有8人。我需要找出并显示从8中选出4个人时创建的所有可能的非重复组合。所选个体的顺序并不重要。我只需要找到所有独特的组合。
例如: 8人是鲍勃,卡罗尔,特德,爱丽丝,里德,苏,约翰尼,本(细胞A1到A8各有一个名字)。
一个组合是鲍勃,泰德,里德,约翰尼。对于我的问题,名字的顺序并不重要,这意味着Bob,Ted,Reed,Johnny与Ted,Bob,Johnny,Reed相同。因此,这四个人的任何组合都算作一个例子。
我不只是想弄清楚有多少组合是可能的。我需要实际看到可能的组合。
答案 0 :(得分:2)
我构建了一个二元评估器:
Public Sub DebugAllCombinations(lPickSize As Long, sPossibilities As String, Optional sDelimiter As String = ";")
Dim i As Long
Dim j As Long
Dim sBIN As String
Dim aPossibilities() As String
Dim lSum As Long
Dim lHitCount As Long
aPossibilities = Split(sPossibilities, sDelimiter)
For i = 1 To 2 ^ (UBound(aPossibilities) + 1) - 1
lSum = 0
sBIN = WorksheetFunction.Dec2Bin(i)
For j = 1 To Len(sBIN)
lSum = lSum + CLng(Mid(sBIN, j, 1))
Next j
If lSum = lPickSize Then
For j = 1 To Len(sBIN)
If Mid(sBIN, j, 1) = "1" Then Debug.Print aPossibilities(Len(sBIN) - j) & sDelimiter;
Next j
Debug.Print
lHitCount = lHitCount + 1
End If
Next i
Debug.Print lHitCount & " possibilities found"
End Sub
您可以像这样使用
DebugAllCombinations 4, "Person1;Person2;Person3;Person4;Person5;Person6;Person7;Person8"
它将在即时窗口中调试
答案 1 :(得分:0)
未经测试,但如果我理解你的问题,我认为应该这样做:
Sub combinationEnumeration(pool As String, elements As Integer, Optional delim As String)
Dim poolArray() As String, result As String
If delim = "" Then delim = ";"
poolArray = Split(pool, delim)
result = "Selection pool: " & pool & vbCr & "Number of selected elements: " & elements & vbCr & vbCr & "Result:" & vbCr
For i = 0 To UBound(poolArray) - 3
For j = i + 1 To UBound(poolArray) - 2
For k = j + 1 To UBound(poolArray)) - 1
For l = k + 1 To UBound(poolArray)
result = result & poolArray(i) & poolArray(j) & poolArray(k) & poolArray(l) & ";" & vbCr
Next l
Next k
Next j
Next i
Debug.Print result
End Sub
用法:Call combinationEnumeration("A;B;C;D;E;F;G;H", 4)
编辑:修正了小错误。代码现在正确并输出预期的结果数。您将获得70行,您可以通过求解二项式C(8,4)
:http://www.wolframalpha.com/input/?i=c%288%2C4%29来仔细检查。
答案 2 :(得分:0)
=COMBIN(number, number_chosen)