Use VBA to loop through files in a folder to automate tasks like renaming, copying, or processing multiple files without manual intervention. This works in Excel, Word, or Access with VBA enabled. You need access to the folder and the files must be accessible by the user account running the code.
What You'll Need
- Microsoft Excel, Word, or Access with VBA enabled (File > Options > Customize Ribbon > check Developer)
- A folder containing files you want to process (e.g., .xlsx, .pdf, .txt)
- Permissions to read and, if needed, modify files in the target folder
- Basic understanding of VBA editor (press Alt+F11 to open)
Step-by-Step
- Open the VBA editor by pressing Alt+F11 in Excel, Word, or Access.
- In the Project Explorer window, right-click on your workbook or document name and select Insert > Module. This creates a new blank code module.
- Copy and paste the following code into the module:
Sub LoopThroughFiles()
Dim FolderPath As String
Dim FileName As String
' Set the folder path - use double backslashes or forward slashes
FolderPath = "C:\YourTargetFolder\" ' Change this path
' Check if folder exists and ends with backslash
If Right(FolderPath, 1) <> "\" Then FolderPath = FolderPath & "\\"
' Initialize file search
FileName = Dir(FolderPath & "*.*")
' Loop through all files in the folder
Do While FileName <> ""
' Display the file name in the Immediate Window (Ctrl+G to open)
Debug.Print FileName
' Add your file processing code here
' Example: Open file, rename, copy, or delete
' Application.Workbooks.Open FolderPath & FileName ' for Excel files
' Get next file
FileName = Dir
Loop
MsgBox "Processing complete. Check Immediate Window for file list."
End Sub
- Replace
C:\YourTargetFolder\with the full path to your target folder. Use double backslashes (\\) or forward slashes (/) to avoid escape character errors. - Press F5 to run the code. The Immediate Window (press Ctrl+G if hidden) will show each filename as it’s processed.
- To process only specific file types, change
*.*to*.xlsx,*.pdf, or*.txtin theDirfunction. - To process subfolders recursively, you need to modify the code to use a recursive function with
FileSystemObjector use Windows API calls — this version loops only the top-level folder. - Test first with a folder containing non-critical files. Add file operations like
Kill(delete),Name(rename), orFileCopyonly after confirming the loop works correctly.
Common Mistakes
- Using single backslashes in file paths (e.g.,
C:\Folder\instead ofC:\\Folder\\) — this causes runtime errors. - Forgetting to end the folder path with a backslash, which breaks the
Dirfunction. - Running the code with no files in the folder — the loop won’t execute, which may be mistaken for a failure.
- Trying to open or modify files that are already open in another program — this causes permission errors.
- Not using
Debug.Printto verify the loop is working — without output, you can’t confirm the code is finding files. - Using
Dirwithout resetting it — if the code stops mid-loop, callingDiragain may return the same file. Always restart withFileName = Dir(FolderPath & "*.*")if restarting the loop.
Tips
- Use
Debug.Printto log filenames during testing — it’s safer than writing to worksheets until you’re certain the logic works. - Wrap file operations in
On Error Resume Nextblocks if some files might be locked or corrupted, then checkErr.Numberafter each operation to log issues. - Store the folder path in a cell on a worksheet (e.g., A1) and reference it with
Range("A1").Valueto make the code reusable without editing the VBA. - Use
FileSystemObject(add a reference in Tools > References > Microsoft Scripting Runtime) for advanced file operations like checking file size, date, or attributes. - For large folders, disable screen updating with
Application.ScreenUpdating = Falseto speed up execution. - Always test with a copy of your data. File operations like deletion or renaming are irreversible.
Troubleshooting
- No files appear in the Immediate Window — Verify the folder path is correct. Test by pasting the path into Windows Explorer. Check for typos, extra spaces, or incorrect drive letters.
- Runtime Error 53: File not found — The folder doesn’t exist or the path is malformed. Use
Dir(FolderPath)by itself to test path validity — if it returns empty, the path is wrong. - Code runs but doesn’t do anything — You may have changed the file filter (e.g.,
*.xlsx) but no files match. Temporarily revert to*.*to confirm the loop works. - Access denied errors — You lack write permissions. Run Excel as Administrator, or choose a folder where you have full control (like your Documents folder).
- Loop stops after one file — You may have accidentally deleted the
FileName = Dirline. This line is essential to fetch the next file. - Code crashes with "Out of Memory" — The folder contains thousands of files. Add
DoEventsinside the loop to yield control to the OS and prevent freezes.
Frequently Asked Questions
Can I loop through files in subfolders too?
Yes, but the basicDir method doesn’t handle recursion. Use the FileSystemObject with a recursive function, or use Windows API calls like FindFirstFile and FindNextFile. This requires more complex code.
Why does my code skip some files?
Files with hidden, system, or read-only attributes may be skipped if you don’t account for them. UseDir(FolderPath & "*.*", vbNormal + vbHidden + vbSystem) to include all files.
Can I use this in Microsoft Word or Access?
Yes. The same code works in Word or Access VBA. TheDir function is part of VBA’s core library and doesn’t depend on Excel-specific objects.
How do I get the full file path in the loop?
Combine the folder path and filename:FullPath = FolderPath & FileName. Always use this full path when opening, copying, or deleting files.
What if the folder path has spaces in it?
Spaces are fine. VBA handles paths with spaces correctly as long as you use proper string syntax (e.g.,"C:\My Documents\\").
Can I sort files by date or name before looping?
Not withDir alone — it returns files in system order. To sort, collect filenames into an array or collection first, then sort them using a custom function before processing.