以下是我的代碼。我想實現通過遞歸方法相同的結果,因爲嵌套循環數從2變化至最大8。VBA遞歸「For循環」排列?
Sub permutation()
c1 = Array(1, 2)
c2 = Array(3, 4)
c3 = Array(5, 6)
c4 = Array(7, 8)
c5 = Array(9, 10)
c6 = Array(11, 12)
c7 = Array(13, 14)
c8 = Array(15, 16)
With Sheets("Criteria")
.Cells.Clear
n = 1
For a = LBound(c1) To UBound(c1)
For b = LBound(c2) To UBound(c2)
For c = LBound(c3) To UBound(c3)
For d = LBound(c4) To UBound(c4)
For e = LBound(c5) To UBound(c5)
For f = LBound(c6) To UBound(c6)
For g = LBound(c7) To UBound(c7)
For h = LBound(c8) To UBound(c8)
Cells(n, 1).Value = c1(a)
Cells(n, 2).Value = c2(b)
Cells(n, 3).Value = c3(c)
Cells(n, 4).Value = c4(d)
Cells(n, 5).Value = c5(e)
Cells(n, 6).Value = c6(f)
Cells(n, 7).Value = c7(g)
Cells(n, 8).Value = c8(h)
n = n + 1
Next h
Next g
Next f
Next e
Next d
Next c
Next b
Next a
End With
End Sub
我還發現一種遞歸代碼示例在互聯網上,但我真的不知道如何根據我的需要進行修改。任何幫助都會非常棒。
遞歸代碼示例
Sub RecurseMe(a, v, depth)
If a > depth Then
PrintV v
Exit Sub
End If
For x = 1 To 4
v(a) = x
a = a + 1
RecurseMe a, v, depth
a = a - 1
Next x
End Sub
Sub PrintV(v)
For J = 1 To UBound(v): Debug.Print v(J) & " ";: Next J
Debug.Print
End Sub
Sub test()
Dim v()
depth = 4 'adjust
a = 1
ReDim v(1 To depth)
RecurseMe a, v, depth
End Sub
問候
你能否重述你的目標?您想做什麼? –
我想將循環數設置爲變量。例如在上面的例子中,我使用了8個循環,所以輸出是2^8 = 256。但有時候我只需要2個例子。所以輸出將是2x2矩陣。 – Shan
它只是填充我的數組中的數據。這個數組的長度是可變的,所以所有的循環根據每個數組的長度運行 – Shan