To get file names from a folder using VBA, you use the Dir function within a Do While loop to iterate through the directory and write each result to a worksheet cell. This process automates the tedious task of manually copying and pasting filenames, making it essential for auditing large directories or creating file indexes.
What You'll Need
- Microsoft Excel installed on a Windows PC.
- A folder containing the files you wish to list.
- The exact file path of that folder (e.g., C:\Users\Documents\Reports).
- Basic access to the Visual Basic Editor (VBE) within Excel.
Step-by-Step
- Open the Visual Basic Editor: Launch your Excel workbook. Press
Alt + F11on your keyboard. This shortcut opens the VBE window where all your macros are written. - Insert a New Module: In the VBE menu, go to
Insertand selectModule. This creates a blank code page. It is important to use a module rather than writing code directly into the "ThisWorkbook" or "Sheet" objects to ensure the macro is available globally within the workbook. - Paste the VBA Code: Copy and paste the following code into the module window:
Sub ListFiles() Dim xFSO As Object Dim xFolder As Object Dim xFile As Object Dim i As Integer Dim folderPath As String ' Set the folder path here folderPath = "C:\Your\Folder\Path\" ' Ensure the path ends with a backslash If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\" End If Set xFSO = CreateObject("Scripting.FileSystemObject") If xFSO.FolderExists(folderPath) Then Set xFolder = xFSO.GetFolder(folderPath) i = 1 ' Clear the current sheet to start fresh Cells.ClearContents Cells(1, 1).Value = "File Name" For Each xFile In xFolder.Files i = i + 1 Cells(i, 1).Value = xFile.Name Next xFile Else MsgBox "Folder not found. Please check the path.", vbCritical End If Set xFSO = Nothing Set xFolder = Nothing Set xFile = Nothing End Sub - Customize the Folder Path: Locate the line
folderPath = "C:\Your\Folder\Path\". Replace the text inside the quotation marks with the actual path to your folder. For example, if your files are in a folder named "Invoices" on your C drive, it should look like"C:\Invoices\". - Run the Macro: You can run the code in two ways. First, while still in the VBE, click the green "Run" arrow in the toolbar or press
F5. Alternatively, go back to your Excel sheet, pressAlt + F8, selectListFilesfrom the list, and clickRun. - Verify the Results: Switch back to your Excel worksheet. You should now see a list of every file located in the specified folder starting from cell A1.
Common Mistakes
One of the most frequent errors occurs with the folder path syntax. In VBA, a path must be a string enclosed in double quotes. A common mistake is forgetting the trailing backslash (\). While the provided code includes a check to add the backslash automatically, manually typing paths often leads to errors if the user forgets that Windows paths use backslashes, not forward slashes.
Another common mistake is running the macro on a protected sheet. If the worksheet is locked or protected, the Cells.ClearContents or Cells(i, 1).Value commands will trigger a "Run-time error '1004': Application-defined or object-defined error." Always ensure the sheet is unprotected before executing the script.
Users also frequently forget to save the workbook in the correct format. A standard .xlsx file cannot store VBA macros. If you save the file as a normal workbook and close it, all your code will be permanently deleted. You must save the file as an Excel Macro-Enabled Workbook (.xlsm).
Lastly, there is the issue of permission levels. If you attempt to pull file names from a restricted system folder (like C:\Windows\System32) or a network drive where you do not have "Read" permissions, the script will crash or return an "Access Denied" error. Always test the path manually in Windows File Explorer first to ensure you have access.
Tips
To make the tool more flexible, instead of hard-coding the path into the script, you can use folderPath = Range("B1").Value. This allows you to simply type the folder path into cell B1 of your spreadsheet and run the macro without ever opening the VBA editor again.
If you only want to list specific types of files, such as PDFs or Excel files, you can add an If statement inside the loop. For example, adding If xFile.Name Like "*.pdf" Then before writing to the cell will filter the list to show only PDF documents.
For those dealing with thousands of files, the screen may flicker as Excel writes each name to a cell, which slows down the process. To speed this up, add Application.ScreenUpdating = False at the very beginning of the macro and Application.ScreenUpdating = True at the very end. This prevents Excel from redrawing the screen until the entire list is complete.
If you need more than just the file name, the FileSystemObject (FSO) provides additional properties. You can change xFile.Name to xFile.Size to get the file size in bytes, or xFile.DateCreated to get the timestamp of when the file was first saved to the disk.
Troubleshooting
If the code does not work, first check for Compile Errors. If the VBE highlights a line in yellow or red, check for missing quotation marks or misspelled variable names. Ensure that the Dim statements at the top match the variables used in the body of the code.
If you receive a "Path not found" message box, double-check the folder path. A common issue is a typo in the folder name or a hidden file extension in Windows that makes the path appear different than it actually is. Copy the path directly from the address bar in File Explorer to be certain.
If the macro does not run at all, check your Macro Security settings. Go to File > Options > Trust Center > Trust Center Settings > Macro Settings. Ensure that "Disable all macros with notification" is selected. When you reopen the file, you must click "Enable Content" in the yellow security bar at the top of the sheet for the code to function.
If the list is incomplete or missing files, check if the files are hidden. By default, some system files are hidden by Windows. The FileSystemObject generally sees these, but if you are using a different method like the Dir function, hidden files may be skipped unless specific attributes are requested.
Frequently Asked Questions
Can I list files in subfolders as well?
The basic code provided only lists files in the top-level folder. To include subfolders, you would need a "recursive" macro, which is a function that calls itself every time it encounters a folder within the main folder.
Will this work on a Mac?
No, the Scripting.FileSystemObject is a Windows-only library. Mac users must use the Dir function or AppleScript to achieve similar results, as the file system architecture is entirely different.
Can I export the list to a text file instead of Excel?
Yes. Instead of using Cells(i, 1).Value, you would use the Open statement in VBA to create a .txt file and the Print # command to write the filenames into that text document.
How do I handle folders with thousands of files?
For very large directories, writing to cells one-by-one is slow. The most efficient method is to load the filenames into a VBA Array first and then write the entire array to the worksheet in one single operation.
Can I filter for only the most recent file?
Yes. You can modify the loop to compare the xFile.DateLastModified property of each file, storing the most recent date in a variable and updating the filename accordingly until the loop finishes.