Excel VBA Recursive Loop: Step-by-Step Guide
In this article
A recursive loop in Excel VBA is a procedure that calls itself to repeat a task until a condition is met. You write it by creating a Function or Sub that includes a test for the stopping condition, calls itself with a smaller or changed input, and returns a result. This is useful for walking folder trees, processing nested ranges, or calculating values that depend on previous results. You do not need any add-ins, but you should save your workbook as .xlsm and enable the Developer tab.
What You'll Need
- Excel desktop version (Windows or Mac) with macros enabled. Recursion is not supported in Excel for the web.
- A workbook saved as .xlsm (macro-enabled).
- The Developer tab visible. If it is not, right-click the ribbon, choose Customize the Ribbon, and tick Developer in the right-hand list. Labels can differ slightly by version.
- A basic understanding of VBA syntax (Sub, Function, If...Then, variables).
Step-by-Step
Open the VBA editor. Press Alt+F11 (Windows) or Fn+Alt+F11 (Mac). In the Project Explorer, right-click your workbook and choose Insert > Module. A blank module appears.
Write a simple recursive function. Start with a factorial example so you can see the pattern clearly. Type the following into the module:
Function Factorial(n As Long) As Long If n <= 1 Then Factorial = 1 Else Factorial = n * Factorial(n - 1) End If End FunctionThe key parts are the base case (n <= 1) that stops the recursion and the recursive call (Factorial(n - 1)) that moves toward the base case.
Test it from the Immediate Window. Press Ctrl+G to open the Immediate Window and type
?Factorial(5), then press Enter. You should see 120. If you see an error, check that the module is in the right workbook and that the function name matches exactly.Add a guard against infinite loops. Recursion in VBA has a stack limit; too many nested calls cause a "Stack space exhausted" or "Out of stack space" error. Add a depth counter as an optional argument:
Function SafeFactorial(n As Long, Optional depth As Long = 0) As Long If depth > 100 Then SafeFactorial = -1 Exit Function End If If n <= 1 Then SafeFactorial = 1 Else SafeFactorial = n * SafeFactorial(n - 1, depth + 1) End If End FunctionAdjust the limit (100 here) to suit your task. For most worksheet tasks a limit of 100 to 200 is safe.
Use recursion to walk a folder tree. This is a common real-world use. The following Sub lists every file in a folder and its subfolders into column A of the active sheet:
Sub ListFiles(ByVal folderPath As String, ByVal rowNum As Long) Dim fso As Object, fld As Object, fil As Object, subFld As Object Set fso = CreateObject("Scripting.FileSystemObject") Set fld = fso.GetFolder(folderPath) For Each fil In fld.Files Cells(rowNum, 1).Value = fil.Path rowNum = rowNum + 1 Next fil For Each subFld In fld.SubFolders ListFiles subFld.Path, rowNum Next subFld End SubRun it with
ListFiles "C:\YourFolder", 1from the Immediate Window. Change the path to a folder you have permission to read.Call a recursive Sub from a normal macro. Because the Sub above takes arguments, you cannot attach it directly to a button. Create a wrapper:
Sub RunListFiles() ListFiles "C:\YourFolder", 1 End SubNow you can assign RunListFiles to a button or run it with Alt+F8.
Test with a small dataset first. Point the folder path at a folder with a handful of files. Check that column A fills correctly and that the macro stops. Only then run it on a large tree.
Save and close. Save the workbook as .xlsm. If you plan to share it, note that macros may be blocked by the recipient's Trust Center settings; they will need to enable macros for the file.
Common Mistakes
- No base case. A recursive procedure without a stopping condition runs until Excel crashes with a stack error. Always write the base case first.
- Base case never reached. If the input does not move toward the base case (for example, you forget to subtract 1), the recursion never ends.
- Using recursion where a loop is simpler. For flat lists, a For Each or Do While loop is faster and easier to debug. Recursion is best for tree-shaped or nested data.
- Forgetting to reset row counters. In the folder example, rowNum is passed ByVal so each call gets its own copy. If you pass it ByRef by mistake, rows overwrite each other.
- Assuming recursion is fast. Each call adds overhead. Deep recursion on thousands of items can be slow; consider a stack-based loop instead.
Tips
- Keep the base case at the top of the procedure so it is the first thing you and Excel see.
- Use
Debug.Printinside the recursive call to trace depth and inputs in the Immediate Window. - Use
Application.EnableEvents = FalseandApplication.ScreenUpdating = Falsearound heavy recursive writes, then set them back to True. - Name the depth argument clearly (depth, level, calls) so future readers know it is a safety valve.
- For folder walks, the FileSystemObject approach above works on both Windows and Mac Excel, but path separators differ; use the folder picker or build paths with the correct separator for your platform.
Troubleshooting
- "Out of stack space" or "Stack space exhausted". Your recursion went too deep or never hit the base case. Add a depth guard and re-check the condition that should stop the calls.
- Macro does nothing. Check that macros are enabled (File > Options > Trust Center > Trust Center Settings > Macro Settings on Windows; Excel > Preferences > Security on Mac). Also confirm the Sub name you run matches the one in the module.
- Wrong results from a recursive Function. Make sure every code path assigns a value to the function name. If a branch does not, VBA returns the default (0 or empty).
- Folder walk misses files. Check permissions on the folder. The FileSystemObject raises an error if a subfolder is inaccessible; wrap the call in
On Error Resume Nextonly if you accept skipping those folders, and reset error handling afterwards. - Excel freezes. Press Esc or Ctrl+Break to interrupt. If that fails, close Excel from Task Manager; unsaved changes will be lost, so save before running long macros.
Frequently Asked Questions
Can VBA do recursion?
Yes. VBA supports recursive Subs and Functions. The main limit is stack space, so deep recursion can fail; add a depth guard.
What is the difference between a recursive loop and a normal loop?
A normal loop repeats in one procedure. A recursive loop repeats by calling the same procedure again with a changed input, which suits nested or tree-shaped data.
Why does my recursive macro crash Excel?
Almost always a missing or unreachable base case. Add a condition that stops the calls and a depth counter as a backup.
Is recursion faster than a For loop in VBA?
No. Recursion has call overhead. Use it for structure, not speed. For flat data, a For Each loop is usually faster.
Can I use recursion to process nested folders?
Yes. The FileSystemObject example above lists files in a folder and all its subfolders by calling itself for each subfolder.
Does recursion work in Excel for the web?
No. VBA macros, including recursive ones, require the desktop version of Excel.