How to Fix Excel VBA Run-Time Error 28 Out of Stack Space

Executing macro automation in Microsoft Excel occasionally terminates abruptly with Run-time error ’28’: Out of stack space. This critical fault indicates that VBA’s execution call stack has exceeded its maximum allocated memory buffer, almost universally caused by uncontrolled recursive function calls or cascading worksheet change events looping indefinitely.

Disable Application Events to Break Infinite Worksheet Cascades

The most frequent cause of Error 28 occurs when a Worksheet_Change event modifies a cell, which instantly triggers the same Worksheet_Change event again in an infinite loop:

  1. Open your workbook and press Alt + F11 to launch the Visual Basic Editor (VBE).
  2. Locate your sheet modules under Microsoft Excel Objects.
  3. Inspect any Worksheet_Change or Workbook_SheetChange subroutines.
  4. Wrap any cell modification statements with Application.EnableEvents = False and restore them afterward:
    Private Sub Worksheet_Change(ByVal Target As Range)
        On Error GoTo CleanExit
        Application.EnableEvents = False
        
        ' Perform your range modifications here
        Target.Offset(0, 1).Value = Now
        
    CleanExit:
        Application.EnableEvents = True
    End Sub
  5. The EnableEvents = False statement prevents Excel from recursively invoking the handler upon its own edits.

Identify and Restructure Infinite Recursive Functions

Recursive algorithms that calculate factorial, directory trees, or mathematical sequences must have an absolute, unreachable base termination condition:

  • Inspect functions that call themselves and verify that internal argument counters decrement or increment reliably toward the base case.
  • Verify that boundary conditions (such as If n <= 1 Then Exit Function) cannot be bypassed by negative or invalid input values.
  • Replace deep recursion with iterative Do While or For...Next loops to utilise heap memory rather than exhausting the limited call stack.

Audit Deeply Nested Subroutine Calls and Redundant Variables

Excessive subroutine chaining and passing massive arrays by value consumes stack frames rapidly:

  1. Ensure large arrays or user-defined types (UDTs) are passed ByRef (by reference) rather than ByVal (by value), avoiding redundant in-memory copies on the stack.
  2. Review circular subroutine dependencies where Procedure A calls Procedure B, which subsequently calls Procedure A.
  3. In the VBE, click Debug > Compile VBAProject to verify project integrity before saving and executing macro batches.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.