Hi!
I'm extremely novice at VBA. I'm trying to mash two codes I found online, but obviously it's not that easy. I'm trying to find a code that will return all permutations without repetition and no row constraint (i.e. the permutation of 10 options with 7 selections).
This is what I have so far:
Any help to make this work would be much appreciated!
TY!</rng(r-1,c)
I'm extremely novice at VBA. I'm trying to mash two codes I found online, but obviously it's not that easy. I'm trying to find a code that will return all permutations without repetition and no row constraint (i.e. the permutation of 10 options with 7 selections).
This is what I have so far:
Code:
Option Explicit
Function ListPermut(num As Integer)
'Permutations without repetition
Dim a As Integer
Dim b As Integer
Dim x As Integer
Dim z As Integer
Dim e As Integer
Dim f As Integer
Dim n As Long
Dim c As Long, r As Long, p As Long
Dim rng() As Long, temp As Long, i As Long
Dim temp1 As Long, y() As Long, d As Long
p = WorksheetFunction.Permut(num, num)
Dim maxRows As Long
Dim sheetNumber As Integer
Dim loopCounter As Integer
maxRows = 1048576
loopCounter = 38
sheetNumber = 1
n = 1
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = "Sheet-" & sheetNumber
Application.ScreenUpdating = False
For a = 1 To loopCounter
For b = 1 To loopCounter
For x = 1 To loopCounter
For z = 1 To loopCounter
For e = 1 To loopCounter
For f = 1 To loopCounter
Cells(n, 1).Value = a
Cells(n, 2).Value = b
Cells(n, 3).Value = x
Cells(n, 4).Value = z
Cells(n, 5).Value = e
Cells(n, 6).Value = f
If n = maxRows Then
sheetNumber = sheetNumber + 1
ActiveWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)
ActiveSheet.Name = "Sheet-" & sheetNumber
n = 0
End If
n = n + 1
Next f
Next e
Next z
Next x
Next b
Next a
Application.ScreenUpdating = False
' Create array
ReDim rng(1 To p, 1 To num)
'Create first row in array (1, 2, 3, ...)
For c = 1 To num
rng(1, c) = c
Next c
For r = 2 To p
' 1. Find the first smaller number rng(r-1, c-1)<rng(r-1,c)
For c = num To 1 Step -1
If rng(r - 1, c - 1) < rng(r - 1, c) Then
temp = c - 1
Exit For
End If
Next c
' Copy values from previous row
For c = num To 1 Step -1
rng(r, c) = rng(r - 1, c)
Next c
' 2. Find a larger number than rng(r-1, temp)as far to the right as possible
For c = num To 1 Step -1
If rng(r - 1, c) > rng(r - 1, temp) Then
temp1 = rng(r - 1, temp)
rng(r, temp) = rng(r - 1, c)
rng(r, c) = temp1
ReDim y(num - temp)
i = 0
For d = temp + 1 To num
y(i) = rng(r, d)
i = i + 1
Next d
i = 0
For d = num To temp + 1 Step -1
rng(r, d) = y(i)
i = i + 1
Next d
Exit For
End If
Next c
Next r
ListPermut = rng
End Function
Any help to make this work would be much appreciated!
TY!</rng(r-1,c)
Last edited by a moderator: