Question

I have a couple of colleagues looking at some bad code in Excel VBA, wondering is there a limit to the number of levels in a call stack

Was it helpful?

Solution

Unless the function is tail-recursive and VBA can handle that (which it can't), you'll run into a stack overflow.

As a simple test I hacked together the following snippet:

Dim count As Integer

Sub Rec()
    count = count + 1
    Cells(1, 1) = count
    Call Rec
End Sub

which tells us that the limit for this is 4007 iterations, at least in my version of Excel 2007 here.

OTHER TIPS

the short answer is yes, eventually you will get a stack overflow exception.

Not sure what the limit is though.

I just ran this macro in Excel 2003, and got 4775 calls deep before I got error 28, "Out of stack space" :

Sub Macro1()
    recurse (0)
End Sub

Sub recurse(level As Long)
   ActiveCell.FormulaR1C1 = Str$(level)
   Call recurse(level + 1)
End Sub

Old question I know, but I thought it might be useful to have some up to date info on this question as I was looking in to it today.

The hard limit seems to be 6801 calls deep for a parameter-less procedure in Excel 2016. As VBA_interested says, this number reduces with the number of parameters to the recursive procedure.

I ran the following tests in Excel 2016:

Sub RecurseStatic (with no parameters) overflowed after 6801 recursions.
Sub Recurse1 (with 1 parameter) overflowed after 6442 recursions.
Sub Recurse2 (with 2 parameters) overflowed after 6120.

Option Explicit

Sub RecurseStatic()
    Static i As Long
    Debug.Print i
    i = i + 1
    RecurseStatic
End Sub

Sub RunRecurse1()
    Recurse1 0
End Sub

Sub Recurse1(i As Long)
    Debug.Print i
    Recurse1 i + 1
End Sub

Sub RunRecurse2()
    Recurse2 0, 0
End Sub

Sub Recurse2(i As Long, j As Long)
    Debug.Print i, j
    Recurse2 i + 1, j + 1
End Sub

I ran Anders' code in Excel 2013 and the result was only 1180. Not sure if they have reduced the recursion limit in newer versions of Excel or if the problem is machine dependent or whatnot.

Edit: Also, changed: ActiveCell.FormulaR1C1 = Str$(level) to Range("A1").FormulaR1C1 = Str$(level)

And the # of calls dropped to 807. I had also had added Option Explicit.

Stack memory consumption.

As i understand the stack if used for storage of parameters to procedures, and for local variables in the procedures.

Therefore will the consumption of stack space, be proportional to number of recursive calls.

So the needed size of the stack is something like: number of recursive calls * (size of calling parameters+ space for local variables)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top