使用宏在多列上生成组合

时间:2013-07-30 09:24:37

标签: vba

根据= COMBIN(20,6),存在38,760种可能的组合。

我需要运行一个可以列出6列所有可能组合的宏。

所以我需要A列中的前6,460种组合,B列中接下来的6,460种组合等,一直到F列。如何使用VBA进行此操作?

1 个答案:

答案 0 :(得分:0)

这是VB-Code的工作原理,我假设您可以自己将结果放入excel-cells ......:)

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