Smart Systems for Home

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

Excel VBA Dir Function: Guide to Listing Files

· 6 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

The Excel VBA Dir function is used to return the name of a file, directory, or folder that matches a specified pattern. It is the primary tool for automating tasks that require scanning a folder for specific files, such as importing multiple CSVs, archiving old reports, or verifying if a specific configuration file exists before running a macro. At its simplest, it checks for a file's existence; at its most powerful, it creates a loop that iterates through every file in a directory.

What You'll Need

  • Microsoft Excel installed on a Windows PC (the Dir function is a VBA command and behaves differently or is unavailable in Mac versions of Excel).
  • The Developer tab enabled in the Excel Ribbon.
  • A folder on your local drive or network containing the files you wish to target.
  • Basic familiarity with the VBA Editor (VBE).

Step-by-Step

  1. Open the VBA Editor: Launch Excel and press Alt + F11. This opens the Visual Basic for Applications window.
  2. Insert a New Module: Go to the Insert menu and select Module. This creates a blank space where you can write your procedure.
  3. Define Your Path and File Pattern: Before calling the Dir function, you must define where the code should look. Create a string variable for the folder path and another for the file extension. For example, if you want all Excel workbooks, use "*.xlsx". The asterisk acts as a wildcard.
  4. Initialize the Dir Function: Use the syntax FileName = Dir(PathAndFilter). The first time you call Dir in a procedure, you must provide the full path and the filter. For example: myFile = Dir("C:\Reports\*.xlsx").
  5. Check for the First Match: The Dir function returns an empty string ("") if no file matching the criteria is found. You should wrap your logic in an If statement or a Do While loop to ensure the code doesn't crash when a folder is empty.
  6. Create a Loop for Multiple Files: To find every file in the folder, use a Do While loop. Inside the loop, call Dir again, but this time without any arguments: myFile = Dir(). This tells VBA to find the next file that matches the original pattern established in step 4.
  7. Process the File: Inside the loop, you can perform actions such as printing the filename to the Immediate Window, writing the name into a cell in your spreadsheet, or opening the workbook to extract data.
  8. Close the Loop: The loop will automatically terminate when Dir() returns an empty string, signaling that there are no more files matching the pattern.

Common Mistakes

One of the most frequent errors is forgetting the trailing backslash in the folder path. If your path is "C:\MyFolder" and your filter is "*.txt", concatenating them results in "C:\MyFolder*.txt", which tells VBA to look for files starting with "MyFolder" in the C: drive, rather than files inside the folder. Always ensure your path ends with a backslash (\).

Another common mistake is attempting to use Dir to find subfolders without specifying the correct attributes. By default, Dir only looks for files. If you need to find directories, you must add the vbDirectory attribute as the second argument: Dir(path, vbDirectory). However, be aware that when using vbDirectory, the function will also return the special . (current directory) and .. (parent directory) entries, which can cause infinite loops if not handled with an If statement to skip them.

Users also often forget that Dir is not recursive. It only looks at the top level of the folder you specify. If you have a folder structure with multiple nested subfolders, a single Dir loop will not find files hidden inside those subfolders. To achieve this, you would need to create a recursive procedure that calls itself every time it encounters a directory.

Tips

To make your code more robust, use the FileSystemObject (FSO) if you need to perform complex tasks like checking file sizes, creation dates, or moving files. While Dir is faster and requires no external references, FSO is more feature-rich. To use FSO, you must go to Tools > References and check Microsoft Scripting Runtime.

When dealing with network paths, use UNC paths (e.g., \\ServerName\SharedFolder\) rather than mapped drives (e.g., Z:\). Mapped drives can vary between different users' computers, whereas UNC paths are universal across the network, making your VBA tool portable for other team members.

If you are searching for a specific file and only need to know if it exists, you don't need a loop. A simple If Dir(fullPath) <> "" Then block is the most efficient way to verify a file's existence before attempting to open it, which prevents the "File Not Found" runtime error.

Troubleshooting

If your code is returning an empty string even though you know files exist, first check the file extensions. Remember that Windows often hides known file extensions. A file that looks like "Report" might actually be "Report.xlsx". Ensure your filter matches the actual extension.

If you encounter a "Path not found" error, verify that the user running the macro has the necessary NTFS permissions to access that folder. VBA cannot "see" folders that the Windows user account is restricted from accessing.

If your loop is running indefinitely or skipping files, ensure you are not calling Dir(somePath) inside the loop. The first call initializes the search; every subsequent call must be Dir() with empty parentheses. If you pass a path into Dir inside the loop, you reset the search to the first file, creating an infinite loop.

If you are working with files that have Unicode characters in their names (non-English characters), Dir may fail or return garbled text. In these instances, switch to the FileSystemObject, as it handles Unicode paths and filenames much more reliably than the legacy Dir function.

Frequently Asked Questions

Can Dir find folders as well as files?

Yes, by using the vbDirectory attribute. However, this will return both files and folders, so you must use the GetAttr function to distinguish between the two if you only want folders.

Is Dir case-sensitive?

No, the Dir function is generally not case-sensitive when searching for filenames on Windows systems, as the underlying Windows file system is case-insensitive.

How do I find files with a specific word in the name?

Use wildcards around the word. For example, Dir("C:\Data\*Invoice*.xlsx") will find any Excel file that has the word "Invoice" anywhere in its filename.

Does Dir work on Mac?

The Dir function has very limited support or behaves differently on macOS. For cross-platform compatibility, it is recommended to use the AppleScriptTask or specific Mac-compatible VBA commands for file handling.

Can I use Dir to delete all files in a folder?

Yes. You can loop through the files using Dir and call the Kill command on each filename returned. Be extremely careful with this, as Kill permanently deletes files without sending them to the Recycle Bin.

What is the difference between Dir and FileSystemObject?

Dir is a built-in VBA function that is very fast and lightweight. FileSystemObject is part of the Scripting library; it is slower but provides much more detail, such as the ability to create folders, check for folder existence, and access file properties like "Date Modified".