在VBA中生成排列

这个问题之前已经被问过 ,但是我找不到一个很容易适用于Excel VBA的答案。

基本上我想做的是这张海报所要求的,但在VBA中。 我想创build一个数组,nx 2 ^ n,其中每一行表示n个variables的不同置换,可以是0或1。

我已经玩了很多年了,很容易做一个负载循环的n集,但是对于variablesn我找不到任何可行的东西。

任何代码或只是build议的方式去这个将不胜感激!

这将列出列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 

如果您不在Excel中并且无法访问这些function,那么这里有一个。 或者如果你有一个大于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