VBA – Nested loops with recursion (Permutations)

There is a new article on the same subject here – https://www.vitoshacademy.com/vba-avoid-nested-loops-with-recursion-part-2/

Everyone knows how ugly it looks from a programming point of view to have 5 or 6 nested loops. But what can you do to avoid this? The answer is pretty simple – try to use recursion.

Imagine that you have to show all four digit combinations of the digits from 1 to 6. Something like this:
embedded_loops

 

The trivial method is to do 4 nested loops and to run them. That is probably the only one I knew before. However, if you would like to use recursion to do it, the code becomes better. And if you want to use N nested loops, the code makes it possible.

Here it comes:

Option Explicit

Sub Main()
    
    Static size         As Long
    Static c            As Variant
    Static arr          As Variant
    Static n            As Long
    
    size = 2
    c = Array(1, 2, 3, 4, 5, 6)
    
    n = UBound(c) + 1
    ReDim arr(size - 1)
    
    EmbeddedLoops 0, size, c, n, arr
    
End Sub

Function EmbeddedLoops(index, k, c, n, arr)
    
    Dim i                   As Variant
    
    If index >= k Then
        PrintArrayOnSingleLine arr
    Else
        For Each i In c
            arr(index) = i
            EmbeddedLoops index + 1, k, c, n, arr
        Next i
    End If

End Function

Public Sub PrintArrayOnSingleLine(myArray As Variant)

    Dim counter     As Integer
    Dim textArray     As String
    
    For counter = LBound(myArray) To UBound(myArray)
        textArray = textArray & myArray(counter)
    Next counter
    
    Debug.Print textArray
    
End Sub

Also in GitHub.

Enjoy it! 😀