VBA recursive “For loops” Permutation?

后端 未结 3 1321
执念已碎
执念已碎 2021-01-25 09:30

Below is my code. I would like to achieve the same result by recursive method because the number of nested loops is varying from 2 to max 8.

Sub permutation()

         


        
3条回答
  •  长发绾君心
    2021-01-25 10:19

    I approached it as a binary problem:

    Public Sub Perms(lCyles As Long)
    
        Dim sBin As String
        Dim i As Long
        Dim j As Long
        Dim n As Long
    
        With Sheets("Criteria")
            .Cells.Clear
            n = 1
            For i = 0 To 2 ^ lCyles - 1
                sBin = WorksheetFunction.Dec2Bin(i)
                sBin = String(lCyles - Len(sBin), "0") & sBin
                For j = 1 To Len(sBin)
                    .Cells(n, j) = IIf(Mid(sBin, j, 1) = "1", j * 2, j * 2 - 1)
                Next j
                n = n + 1
            Next i
        End With
    
    End Sub
    

提交回复
热议问题