根据 =COMBIN(20,6),存在 38,760 种可能的组合。
我需要运行一个可以列出超过 6 列的所有可能组合的宏。
所以我需要 A 列中的前 6,460 个组合,B 列中接下来的 6,460 个组合等,一直到 F 列。我如何使用 VBA 来做到这一点?
根据 =COMBIN(20,6),存在 38,760 种可能的组合。
我需要运行一个可以列出超过 6 列的所有可能组合的宏。
所以我需要 A 列中的前 6,460 个组合,B 列中接下来的 6,460 个组合等,一直到 F 列。我如何使用 VBA 来做到这一点?
这是有效的 VB 代码,我假设您可以自己将结果放入 excel 单元格中...... :)
Private Sub Form_Load()
'This is the call that inits the recursion
CombineNumbers 20, 6
End Sub
Private Function CombineNumbers(Num_Elements As Long, Num_Selected As Long) As String()
Dim Buff() As String
ReDim Buff(BinomCoeff(Num_Elements, Num_Selected) - 1)
CombineNumbersRecursion 1, Num_Elements, Num_Selected, Buff, 0&
Dim Value
For Each Value In Buff
Debug.Print Value
Next Value
End Function
Private Sub CombineNumbersRecursion(Start_Element As Long, End_Element As Long, _
Num_Selected As Long, Buff() As String, BuffStartIndex As Long, _
Optional CurrStr As String = vbNullString)
If (Num_Selected) Then
'Recursion
Dim i As Long
For i = Start_Element To End_Element
CombineNumbersRecursion i + 1, End_Element, Num_Selected - 1&, Buff, _
BuffStartIndex, IIf(Len(CurrStr), CurrStr & ", " & CStr(i), CStr(i))
Next i
Else
'Break recursion
Buff(BuffStartIndex) = CurrStr
BuffStartIndex = BuffStartIndex + 1&
Exit Sub
End If
End Sub
Private Function BinomCoeff(n As Long, k As Long) As Long
Dim i As Long
BinomCoeff = 1&
For i = 1& To k
BinomCoeff = BinomCoeff * ((n + 1& - i&) / i&)
Next i
End Function
问候,
AKDA