Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

VBA Dir Not Working? Fix File Search Errors

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

If Dir is not working, the usual cause is one of four things: the path you passed is wrong or lacks a trailing backslash, the file is hidden or in a location the macro cannot see, the current directory has changed under you, or you reused Dir without the empty-argument loop and it has already returned everything. Dir is a simple function — it returns the first matching file name, then returns the next match each time you call Dir with no arguments, and finally returns an empty string when there is nothing left. Almost every "not working" report is a misunderstanding of that stateful behaviour or a path problem, not a broken Office installation.

What You'll Need

  • Excel, Word, Access or any Office app with the VBA editor (press Alt+F11 to open it).
  • The exact folder path you intend to search, copied rather than typed if possible.
  • A spare module where you can paste a short test procedure.
  • Knowledge of whether the files you want are visible in Windows Explorer with "Hidden items" turned on.

Step-by-Step

  1. Print the path you are actually passing. Before blaming Dir, confirm the string is what you think. Add a line such as Debug.Print "[" & myPath & "]" and look in the Immediate window (Ctrl+G). Square brackets reveal stray spaces, missing backslashes and line breaks that are invisible in the code.
  2. Make sure the folder part ends with a backslash. Dir("C:\Reports*.xlsx") looks in the parent folder for a file whose name begins with "Reports", not inside the Reports folder. It must be Dir("C:\Reports\*.xlsx"). This single missing character explains a large share of failures.
  3. Test with a literal path before using variables. Replace the variable with a hard-coded path you copied from Explorer and run it once. If the literal works and the variable does not, the bug is in how the string is built — often a concatenation that drops a separator, or a cell value with a trailing space.
  4. Handle the empty result explicitly. The very first call returns an empty string when nothing matches, and that is not an error. Store it and check: fileName = Dir(myPath), then If fileName = "" Then MsgBox "Nothing found". Code that jumps straight into Do While Len(Dir(myPath)) > 0 will loop forever, because each pass restarts the search from the beginning.
  5. Use the two-part loop correctly. The pattern is: one call with the path and pattern, then repeated calls with no arguments. For example fileName = Dir(pattern) followed by Do While fileName <> "" ... fileName = Dir ... Loop, with the next call at the end of the loop body. Calling Dir with a pattern inside the loop resets the sequence and you will process the first file endlessly.
  6. Turn on hidden and system files if needed. Dir only reports normal files by default. To include hidden files, pass the attribute argument: Dir(pattern, vbHidden), or combine values such as vbHidden + vbSystem. You cannot match everything in one pass — vbDirectory combined with other flags still excludes some entries — so run separate passes for normal and hidden files if you need both.
  7. Check the current directory trap. A bare pattern like Dir("*.csv") searches the process's current directory, which can change when the user opens or saves a file through a dialog. Always pass a fully qualified path. If you must rely on the current folder, read it with CurDir and print it to confirm it is where you expect.
  8. Break long folder names into the short 8.3 form if needed. Paths containing spaces are fine when passed correctly, but if a path exceeds the older maximum length that Dir can handle, the call silently returns nothing. Copy the file to a shallower folder to test, or use the Windows short path name for deeply nested directories.
  9. Confirm the drive is mapped in the same session. A network drive mapped with a letter is visible to Explorer but not always to your macro if the mapping belongs to a different user or a non-interactive session. Use the full UNC path (\\server\share\folder\) instead of Z:\folder\ and test again.
  10. Match the pattern syntax, not regex. Dir uses DOS-style wildcards only. * matches any run of characters and ? matches exactly one. Patterns like [0-9]* or *.xls? behave differently than you might expect; *.xls? will also return .xlsx and even names ending in other characters, so check extensions separately if precision matters.
  11. Watch for a re-entrant call in your own code. Any function you call inside the loop that itself uses Dir — even indirectly, such as a helper that checks whether a file exists — destroys the enumeration state. Keep the loop body free of other Dir calls, or collect the names into an array first and process them afterwards.

Common Mistakes

  • No trailing backslash on a folder path, so the last folder name is treated as a file-name prefix.
  • Forgetting Dir is stateful. It is not a pure function; it remembers where it left off, and any other Dir call elsewhere resets it unpredictably.
  • Assuming an empty result is an error. It just means no match — including when the folder does not exist at all.
  • Expecting an exception for a bad path. Dir returns an empty string rather than raising an error, so On Error handlers never fire.
  • Comparing case-sensitively with = in some contexts. File systems are generally case-insensitive, so compare names with StrComp(..., vbTextCompare) when you need reliability.
  • Confusing files and folders. vbDirectory returns the special entries . and .., which you must skip before recursing or listing.

Tips

  • Build a tiny utility procedure that lists every match into the Immediate window before you write any real logic. Seeing the names confirms the pattern, path and attributes in one shot.
  • Store the pattern in a variable so you can swap it while debugging without editing several lines.
  • Prefer FileSystemObject from the Scripting Runtime when you need attributes, sizes or recursion — it handles those cases more cleanly — and keep Dir for quick flat listings.
  • Trim input strings with Trim and test for an empty pattern before calling Dir, since an empty pattern can return unexpected results.
  • When a macro works for you but not for a colleague, suspect drive letters, permissions or hidden files rather than the code.

Troubleshooting

If Dir still returns nothing, work outward from the simplest check. Confirm the folder exists in Explorer and that you can see at least one matching file with hidden items enabled. Run MsgBox Dir("C:\Windows\win.ini") — a file present on virtually every Windows system — to prove the function itself works. If that returns a name, your pattern or path is at fault; if it returns nothing, the macro's environment is the problem. Unsaved work is at risk whenever you test macros that delete or move files, so save your workbook first.

Next, test the same path from a brand-new workbook in the same Office app to rule out a corrupted project, and compile the project (Debug > Compile) to catch a broken reference. If a reference to an object library is marked "MISSING" in Tools > References, many built-in functions misbehave until it is cleared. After that, check whether the folder is synced by a cloud client that keeps files as online-only placeholders; those entries may not appear until downloaded, and you should download them first rather than altering permissions. If the code runs on another machine, verify that user's access rights to the folder — a permissions failure looks identical to "no files." Only as a last resort, repair Office from the Windows settings if every user-defined function misbehaves; this does not delete your documents.

Frequently Asked Questions

Why does Dir return an empty string even though I can see the files?

The files are probably hidden, have an extension that does not match your pattern, or live in a folder whose path is spelled differently from what you passed. Check the path with brackets printed, then test with the hidden attribute argument.

Can I use Dir to search subfolders automatically?

No. Dir lists only one folder at a time. You must call Dir with vbDirectory to find subfolder names, skip . and .., and recurse yourself, or use the FileSystemObject.

Why does my loop never end?

You are calling Dir with the pattern inside the loop, which restarts the enumeration. Call it with no arguments at the end of the body instead.

Does Dir work on network drives and OneDrive folders?

It works when the path is reachable by the macro's user in that session. UNC paths are more reliable than mapped letters, and cloud placeholder files may not be listed until they are downloaded locally.

Why does Dir find files on my PC but not on a colleague's?

Different drive mappings, permissions or file visibility settings. Prefer full paths, confirm the account can open the folder in Explorer, and ask whether hidden items are enabled.

Is there a limit on how many files Dir can return?

There is no fixed count, but very long paths can exceed what Dir handles and produce no results. Test from a shorter path if a folder is deeply nested.