Sub combinations()
Dim numbers, output(), v
Dim d As Object
Dim i As Long, j As Long
Dim s As String
numbers = "1,2,3,4,5,6,7,8"
numbers = Split(numbers, ",")
Set d = permute(UBound(numbers) + 1)
ReDim output(1 To d.count, 1 To 1)
i = 0
For Each v In d.items
i = i + 1
s = ""
For j = 1 To UBound(v)
s = s & IIf(s = "", "", ",") & numbers(v(j) - 1)
Next j
output(i, 1) = s
Next v
Workbooks.Add.Sheets(1).Range("A1").Resize(UBound(output), UBound(output, 2)).Value = output
Set d = Nothing
Erase output
End Sub
Public Function permute(n As Integer) As Object
Dim P() As Integer, permSet() As Integer
Dim t As Integer, i As Integer, j As Integer, k As Integer
Dim count As Long
Dim Last As Boolean
Dim d As Object
If n <= 1 Then
Debug.Print "Please give a number greater than 1"
Exit Function
End If
'Initialize
Set d = CreateObject("Scripting.Dictionary")
ReDim P(n)
For i = 1 To n
P(i) = i
Next i
count = 0
Last = False
Do While Not Last
ReDim permSet(n)
For t = 1 To n
permSet(t) = P(t)
'Debug.Print P(t);
Next
'Debug.Print
count = count + 1
d.Add count, permSet
Last = True
i = n - 1
Do While i > 0
If P(i) < P(i + 1) Then
Last = False
Exit Do
End If
i = i - 1
Loop
j = i + 1
k = n
While j < k
' Swap p(j) and p(k)
t = P(j)
P(j) = P(k)
P(k) = t
j = j + 1
k = k - 1
Wend
j = n
While P(j) > P(i)
j = j - 1
Wend
j = j + 1
'Swap p(i) and p(j)
t = P(i)
P(i) = P(j)
P(j) = t
Loop 'While not last
Debug.Print "Number of permutations: "; count
Set permute = d
End Function