在VBA中生成排列列表

时间:2018-02-02 17:22:17

标签: arrays excel vba algorithm

如何在没有n个嵌套循环的情况下,如何在VBA中生成n个父项和m个子项的组合列表?我最终会得到m ^ n个组合。

这是一个例子。让我们说我有n = 3个父母(1到3)和m = 2个孩子(1到2个)。我想生成以下数组:

1 1   1 2   1 1   1 2   1 1   and so forth...(total of 8)
2 1   2 1   2 2   2 2   2 1
3 1   3 1   3 1   3 1   3 2

这些数组反过来会被用来索引另一个数据数组,所以我最终会选择每个父分支的子进程并拥有它们的所有组合。如果父项的数量与嵌套循环不变,我想办法如何做到这一点,但这是一个问题,因为父项的数量n是可变的。

1 个答案:

答案 0 :(得分:2)

有趣的拼图。

Sub KJK()
Dim parent As Long, child As Long
parent = 3
child = 2
Dim oarr As Variant
ReDim oarr(1 To parent, 1 To child ^ parent)
Dim i As Long, j As Long
For i = 1 To parent
    For j = 1 To child ^ parent
        oarr(i, j) = i & " " & Int(((j - 1) Mod (child ^ i)) / (child ^ i) * child) + 1
    Next j
Next i
'Output the array
Worksheets("Sheet1").Range("A1").Resize(parent, child ^ parent).Value = oarr
End Sub

产生

enter image description here

一个注意事项:如果粘贴到工作表上,子项^父项不能超过16384的列数。