The "VBA Runtime Error 67: Too many files" in Excel macros means your VBA code is trying to open more files than VBA can handle simultaneously—usually because it’s looping through too many records or opening files without proper error handling. This error is common when working with large datasets, looping through multiple sheets, or attempting to process hundreds of files at once. Here’s what to try first, step by step.
What You'll Need
- Excel with VBA enabled (Excel 2010 or later)
- Your problematic macro or VBA project open in the VBA editor
- Access to the files your macro is trying to process (or a test folder with fewer files)
- Optional: A helper macro or script to debug file paths/processing limits
Step-by-Step
-
Check for infinite or excessive loops.
- Open Excel and press Alt+F11 to open the VBA editor.
- Navigate to the module containing your error-prone code. Press Ctrl+Shift+F to search for keywords like "For," "Do While," or "Worksheets(i)" (which often triggers this error).
- Look for loops that:
- Iterate through every worksheet in a workbook (e.g., `For i = 1 To Workbooks.Count`),
- Process rows or files without a clear exit condition (e.g., a counter that never resets), or
- Open files sequentially without tracking progress (e.g., `For Each file In FileSystemObjects.GetFolder(folder).Files`).
Fix: Restructure loops to:
- Use upper-bound limits (e.g., `For i = 1 To maxSheets`), or
- Add a `Exit For` or `Exit Sub` when processing completes, or
- Replace `For Each` with error-checking loops (see Step 3).
-
Add error handling around file operations.
- Wrap file-related code in a
On Error Resume Nextblock (temporarily) to suppress errors during testing. - Replace generic loops with explicit checks. For example:
Option Explicit Sub ProcessFiles() Dim filePath As String Dim maxTries As Integer maxTries = 100 'Limit attempts per file filePath = "C:\TestFolder\*" Dim files() As String files = Dir(filePath) Do While files <> "" 'Process one file at a time ProcessSingleFile files(0) files = Dir 'Move to next file If maxTries = 0 Then Exit Sub 'Exit if limit reached Loop End Sub Sub ProcessSingleFile(fileName As String) On Error Resume Next 'Skip errors during testing Dim fileHandle As Object Set fileHandle = CreateObject("Scripting.FileSystemObject") If fileHandle.FileExists(fileName) Then 'Process file safely Debug.Print "Processing " & fileName Else Debug.Print "Skipping missing: " & fileName End If On Error GoTo 0 'Reset error handling End Sub
- Wrap file-related code in a
-
Replace "For Each" loops with error-safe alternatives.
- If your macro uses `For Each ws In Workbooks("Book1").Worksheets`, replace it with:
For i = 1 To Worksheets.Count On Error Resume Next 'Skip invalid sheets Set ws = ThisWorkbook.Worksheets(i) If Not ws Is Nothing Then 'Process valid sheets End If On Error GoTo 0 Next i - For file operations, use `Dir` + `Loop` instead of `For Each` in FileSystemObjects, or loop through arrays explicitly.
- If your macro uses `For Each ws In Workbooks("Book1").Worksheets`, replace it with:
-
Cap the number of concurrent files processed.
- Modify code to open files sequentially rather than in parallel (VBA’s default behavior).
- Add delays between operations if needed:
Application.Wait Now + TimeValue("00:00:05") - Reduce the size of your loop variables. For example, if processing 1,000 files, split the work into batches of 100:
For batchNum = 1 To ceil(totalFiles / batchSize) ProcessBatch batchNum Next batchNum
-
Test with a smaller subset of files.
- Create a test folder with only 10–20 files, and run the macro on those first.
- Use wildcards to specify a subset:
filePath = "C:\TestFolder\*.csv" 'Limit to .csv files only - If the error persists, identify the file causing the issue and debug its specific path.
If That Did Not Work
- Check for
Application.ScreenUpdatingorApplication.Automationtoggles set to False. Enable them if disabled (they can affect macro performance): - Go to
VBA > Macros > Tools > Options(or press Alt+F11 > Tools > Options). - Uncheck "Disable Screen Updating" and "Disable Events."
- Restart Excel to clear potential background processes.
- Disable other add-ins that might interfere with macros:
- Press Alt+F11 > Tools > References and uncheck any unnecessary references (e.g., "Microsoft Scripting Runtime").
- Go to
Excel Options > Add-ins > Manage Excel Add-insand disable non-essential add-ins.
- Recompile the VBA project. Right-click the project in the Project Explorer and select
Compile VBAProject. - If you’re still stuck, record a new macro with the "Process Files" method from Step 3 to isolate the problematic code.
Common Mistakes
-
Assuming VBA can handle thousands of files simultaneously.
VBA defaults to 1 file per thread. Looping through 1,000 files triggers the "Too many files" error because VBA can’t open that many at once. Always process files sequentially or batch them.
-
Using `For Each` without error handling.
If a sheet or file doesn’t exist, `For Each` throws an error unless you wrap it in `On Error Resume Next`. Without this, the error propagates to your macro.
-
Ignoring Excel’s built-in limits.
- Excel has a 32,000-cell limit per sheet (though some add-ins push this higher).
- The VBA project itself has a 256-character limit for variable names (use named ranges if needed).
-
Opening files in a loop without clearing references.
If you reuse `Set fileHandle = CreateObject("Scripting.FileSystemObject")` in every loop, you risk memory leaks. Always reset references or use a fresh object.
Tips
-
Use named ranges or arrays for file paths.
Instead of hardcoding file paths, define them as arrays or named ranges to avoid typos and simplify looping:
Dim filesToProcess() As String filesToProcess = Array("C:\Book1.xlsx", "C:\Book2.xlsx") For Each file In filesToProcess 'Process file Next file -
Monitor memory usage.
If your macro runs slowly or crashes, check the Immediate Window (Ctrl+G) for memory errors like "Out of memory." Close unused Excel windows or sheets before running the macro.
-
Leverage Excel’s built-in functions.
Replace VBA loops with Excel functions like `INDEX`, `MATCH`, or `TEXTJOIN` where possible. These don’t require VBA and often handle large datasets more efficiently.
-
Test in a clean environment.
Create a new workbook and copy your macro into it. Avoid macros that reference other workbooks or external data sources unless you’ve tested them.
-
Use the Debugger.
Set breakpoints in your VBA code and step through loops to see where the error occurs. Right-click a line and select
Set Breakpoint.
Troubleshooting
-
The error persists after restructuring loops.
- Check for recursive calls. If your macro calls itself (e.g., `Sub ProcessFiles()` calls `ProcessFiles` again), the loop will never exit, causing the "Too many files" error.
- Enable verbose error messages:
On Error Resume Next 'Add this to your code to see where the error originates 'Example output will show "Subname" and line number
-
Macro runs but doesn’t finish.
- Add a `DoEvents` call after each file to release the GIL (Global Interpreter Lock):
DoEvents Application.Wait Now + TimeValue("00:00:01") - Check for deadlocks. If Excel or other apps are open during macro execution, they may block VBA. Close interfering apps or run the macro in a separate session.
- Add a `DoEvents` call after each file to release the GIL (Global Interpreter Lock):
-
Files are being processed but the error still occurs.
- Run the macro in Safe Mode to exclude third-party add-ins:
- Close Excel.
- Open a Command Prompt and run:
excel.exe /safe
- Check for antivirus blocking VBA. Temporarily disable your antivirus or add Excel to its exclusion list.
- Run the macro in Safe Mode to exclude third-party add-ins:
-
Data corruption or slow performance.
- Repair Excel’s registry or restore from a backup. Go to
File > Options > Save > Advanced > Clear Personal Settingsand restart Excel. - Disable macros temporarily to rule out conflicts:
- Go to
File > Options > Trust Center > Trust Center Settings > Macro Settings. - Set macro settings to "Disable all macros with notification." Run your macro and test if it works, then re-enable macros.
- Go to
- Repair Excel’s registry or restore from a backup. Go to
Frequently Asked Questions
Why does my VBA code say "Too many files" when I only have 50 files?
VBA’s default behavior is to open one file at a time. If your loop processes files without awaiting completion, Excel/VBA may treat the total potential open files as a limit. Restructure your code to open files sequentially or use arrays with error handling.
How do I find out which specific file is causing the error?
Add this line before your file loop:
Debug.Print "Error before processing: " & Err.Description
Then enable the Immediate Window (Ctrl+G) and run the macro. The debug output will show the exact file or line causing the issue.
Can I use VBA to process files in parallel?
Technically yes, but VBA’s threading is limited. Use the Application.Run method to offload tasks to another instance of Excel or a helper macro. For true parallel processing, consider alternatives like Python (with libraries like `pandas`) or Excel’s built-in tools.
What if I’m processing Excel files and get this error?
For Excel files, use the Workbooks.Open method with a timeout:
Dim wb As Workbook
Set wb = Workbooks.Open(Filename, ReadOnly:=True, FullPath:=True)
Application.Wait Now + TimeValue("00:00:01") 'Avoid blocking
If the file is locked, wait for it to close or use error handling to skip it.
How do I check if VBA is already running another instance of my macro?
Use this code to detect active instances:
Private Declare PtrSafe Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" () As LongPtr
Private Declare Function OpenProcess Lib "kernel32" Alias "OpenProcess" Handle As LongPtr, _
dwDesiredAccess As Long, _
bInheritHandle As LongPtr
Private Declare Function EnumProcessModules Lib "kernel32" Alias "EnumProcessModules" _
Handle As LongPtr, _
ByRef lpcbNeeded As LongPtr, _
lpMods As LongPtr, _
lpBytesReturned As LongPtr
Private Declare Function CloseHandle Lib "kernel32" Handle As LongPtr
Public Function IsVBARunning() As Boolean
Dim hProcess As LongPtr
Dim hModule As LongPtr
Dim bytesReturned As LongPtr
Dim moduleName As String * 256
Dim moduleNameLen As LongPtr
'Check for Excel or VBA-specific processes
hProcess = OpenProcess & (16 + 32 + 64), 0, 0 'PROCESS_QUERY_INFORMATION + PROCESS_VM_READ + PROCESS_QUERY_LIMIT_INFORMATION
If hProcess = 0 Then Exit Function
EnumProcessModules hProcess, 0, 0, bytesReturned
If bytesReturned = 0 Then Exit Function
moduleNameLen = bytesReturned
moduleName = Space(moduleNameLen)
EnumProcessModules hProcess, Len(moduleName), @moduleName, bytesReturned
IsVBARunning = InStr(1, moduleName, "excel.exe") > 0 Or _
InStr(1, moduleName, "vba.exe") > 0
CloseHandle hProcess
End Function
Run this in a module to see if another instance of Excel is open.
Is there a way to increase VBA’s file limit?
No, VBA’s runtime does not have a configurable "maximum files" setting. The error is a design limitation—process files sequentially or batch them. For extreme cases, consider exporting data to a temporary CSV and processing that with a simpler script.