在VBA中生成排列

时间:2014-08-01 15:00:52

标签: excel algorithm vba excel-vba

This question has been asked before,但我找不到一个易于应用于Excel VBA的答案。

基本上我想做的就是这张海报所要求的,但在VBA中。我想创建一个数组,n x 2 ^ n,其中每一行代表n个变量的不同排列,可以是0或1。

我已经玩了好几年了,对于带有大量循环的集合n来说很容易做到,但是对于变量n我找不到任何有用的东西。

任何代码或只是建议如何处理这个问题将非常感谢!

2 个答案:

答案 0 :(得分:2)

这将列出 A

列中的值
Sub EasyAsCounting()
    Dim N As Long, M As Long, K As Long
    N = Application.InputBox(Prompt:="Enter N", Type:=1)
    M = 2 ^ N - 1
    For K = 0 To M
        Cells(K + 1, 1) = "'" & Application.WorksheetFunction.Dec2Bin(K, N)
    Next K
End Sub

修改#1

仅将数组存储在 VBA 中:

Sub EasyAsCounting()
    Dim N As Long, M As Long, K As Long, ary, s As String
    Dim J As Long
    N = Application.InputBox(Prompt:="Enter N", Type:=1)
    M = 2 ^ N - 1
    ReDim ary(1 To M + 1, 1 To N)
    For K = 0 To M
        s = Application.WorksheetFunction.Dec2Bin(K, N)
        For J = 1 To N
            ary(K + 1, J) = Mid(s, J, 1)
        Next J
    Next K
    '
    'display the array
    '
    msg = ""
    For K = 1 To M + 1
        For J = 1 To N
            msg = msg & " " & ary(K, J)
        Next J
        msg = msg & vbCrLf
    Next K
    MsgBox msg
End Sub

答案 1 :(得分:1)

如果您不在Excel中并且无法访问这些功能,那么这是一个。或者,如果您的数字大于511。

Sub MakePerms()

    Dim i As Long, j As Long
    Dim n As Long
    Dim aPerms() As Byte
    Dim lCnt As Long
    Dim sOutput As String

    Const lVar As Long = 4

    ReDim aPerms(1 To 2 ^ lVar, 1 To lVar)

    For i = 0 To UBound(aPerms, 1) - 1
        n = i
        lCnt = lVar
        aPerms(i + 1, lCnt) = CByte(n Mod 2)
        n = n \ 2
        Do While n > 0
            lCnt = lCnt - 1
            aPerms(i + 1, lCnt) = CByte(n Mod 2)
            n = n \ 2
        Loop
    Next i

    For i = LBound(aPerms, 1) To UBound(aPerms, 1)
        sOutput = vbNullString
        For j = LBound(aPerms, 2) To UBound(aPerms, 2)
            sOutput = sOutput & Space(1) & aPerms(i, j)
        Next j
        Debug.Print sOutput
    Next i

End Sub