You can use the built-in Dir function or the FileSystemObject.
-
Dir Function: VBA: Dir Function
-
FileSystemObject: VBA: FileSystemObject — Files Collection
They each have their own strengths and weaknesses.
Dir Function
The Dir Function is a built-in, lightweight method to get a list of files. The benefits for using it are:
- Easy to Use
- Good performance (it’s fast)
- Wildcard support
The trick is to understand the difference between calling it with or without a parameter. Here is a very simple example to demonstrate:
Public Sub ListFilesDir(ByVal sPath As String, Optional ByVal sFilter As String)
Dim sFile As String
If Right(sPath, 1) <> "" Then
sPath = sPath & ""
End If
If sFilter = "" Then
sFilter = "*.*"
End If
'call with path "initializes" the dir function and returns the first file name
sFile = Dir(sPath & sFilter)
'call it again until there are no more files
Do Until sFile = ""
Debug.Print sFile
'subsequent calls without param return next file name
sFile = Dir
Loop
End Sub
If you alter any of the files inside the loop, you will get unpredictable results. It is better to read all the names into an array of strings before doing any operations on the files. Here is an example which builds on the previous one. This is a Function that returns a String Array:
Public Function GetFilesDir(ByVal sPath As String, _
Optional ByVal sFilter As String) As String()
'dynamic array for names
Dim aFileNames() As String
ReDim aFileNames(0)
Dim sFile As String
Dim nCounter As Long
If Right(sPath, 1) <> "" Then
sPath = sPath & ""
End If
If sFilter = "" Then
sFilter = "*.*"
End If
'call with path "initializes" the dir function and returns the first file
sFile = Dir(sPath & sFilter)
'call it until there is no filename returned
Do While sFile <> ""
'store the file name in the array
aFileNames(nCounter) = sFile
'subsequent calls without param return next file
sFile = Dir
'make sure your array is large enough for another
nCounter = nCounter + 1
If nCounter > UBound(aFileNames) Then
'preserve the values and grow by reasonable amount for performance
ReDim Preserve aFileNames(UBound(aFileNames) + 255)
End If
Loop
'truncate the array to correct size
If nCounter < UBound(aFileNames) Then
ReDim Preserve aFileNames(0 To nCounter - 1)
End If
'return the array of file names
GetFilesDir = aFileNames()
End Function
File System Object
The File System Object is a library for IO operations which supports an object-model for manipulating files. Pros for this approach:
- Intellisense
- Robust object-model
You can add a reference to to «Windows Script Host Object Model» (or «Windows Scripting Runtime») and declare your objects like so:
Public Sub ListFilesFSO(ByVal sPath As String)
Dim oFSO As FileSystemObject
Dim oFolder As Folder
Dim oFile As File
Set oFSO = New FileSystemObject
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
Debug.Print oFile.Name
Next 'oFile
Set oFile = Nothing
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
If you don’t want intellisense you can do like so without setting a reference:
Public Sub ListFilesFSO(ByVal sPath As String)
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
For Each oFile In oFolder.Files
Debug.Print oFile.Name
Next 'oFile
Set oFile = Nothing
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
Return to VBA Code Examples
In this tutorial, you will learn how to get names of all files in a folder and put them into a Worksheet.
Instead, if you want to learn how to check if a file exists, you can click on this link: VBA File Exists
Using the FileSystemObject to Get the List of Files in a Folder
VBA allows you to list all files from a folder, using the FileSystemObject.
We will show how to get a list of files in the folder C:VBA Folder and put it into the first column of the Worksheet. This folder consists of 5 files, as shown in Image 1:
Image 1. Files in folder C:VBA Folder
Here is the code:
Sub LoopThroughFiles ()
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:VBA Folder")
For Each oFile In oFolder.Files
Cells(i + 1, 1) = oFile.Name
i = i + 1
Next oFile
End Sub
In the example, first create an object of the class Scripting.FileSystemObject:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Then set the folder using the method GetFolder:
Set oFolder = oFSO.GetFolder("C:VBA Folder")
Next loop through each file in oFolder, using oFile.Name to get the name of every file in the folder and write it in the next empty row:
For Each oFile In oFolder.Files
Cells(i + 1, 1) = oFile.Name
i = i + 1
Next oFile
Image 2. Worksheet with the list of files in the folder
As you can see in Image 2, all 5 files from the C:VBA Folder are listed in the first column.
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
Получение списка файлов в указанной папке с помощью кода VBA Excel. Коллекция Files объекта Folder, возвращенного методом FileSystemObject.GetFolder.
Коллекция Files объекта Folder
Для получения списка файлов в указанной папке используется свойство Files
объекта Folder
. Объект Folder
в VBA Excel возвращается методом GetFolder
объекта FileSystemObject по полному имени папки в качестве аргумента.
Если в указанной папке нет файлов, применение свойства Folder.Files
приведет к возникновению ошибки. Для корректного завершения программы используйте обработчик ошибок или условие, проверяющее наличие файлов в папке.
Получение списка файлов в папке
Пример 1
Код VBA Excel для получения списка файлов в указанной папке и записи полных имен файлов в массив (с поздней привязкой объектов к переменным):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Sub Primer1() Dim fso, myPath, myFolder, myFile, myFiles(), i ‘Записываем в переменную myPath полное имя папки myPath = «C:DATAТекущая папка» ‘Создаем новый экземпляр FileSystemObject Set fso = CreateObject(«Scripting.FileSystemObject») ‘Присваиваем переменной myFolder ссылку на объект Folder Set myFolder = fso.GetFolder(myPath) ‘Проверяем, есть ли файлы в папке myFolder If myFolder.Files.Count = 0 Then MsgBox «В папке «» & myPath & «» файлов нет» Exit Sub End If ‘Задаем массиву размерность ReDim myFiles(1 To myFolder.Files.Count) ‘Загружаем в массив полные имена файлов For Each myFile In myFolder.Files i = i + 1 myFiles(i) = myFile.Path Next ‘Просматриваем первый элемент массива MsgBox myFiles(1) End Sub |
Используемые переменные:
- fso – ссылка на экземпляр объекта FileSystemObject;
- myPath – полное имя папки;
- myFolder – ссылка на объект Folder (папка);
- myFile – ссылка на один объект File из коллекции myFolder.Files;
- myFiles() – массив для записи имен файлов;
- i – счетчик элементов массива.
Пример 2
Получение списка файлов в указанной папке и запись имен файлов в ячейки первого столбца рабочего листа Excel (с ранней привязкой объектов к переменным):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Sub Primer2() Dim myPath, myFolder As Folder, myFile As File, i ‘Записываем в переменную myPath полное имя папки myPath = «C:DATAТекущая папка» ‘Создаем новый экземпляр FileSystemObject Dim fso As New FileSystemObject ‘Присваиваем переменной myFolder ссылку на объект Folder Set myFolder = fso.GetFolder(myPath) ‘Проверяем, есть ли файлы в папке myFolder If myFolder.Files.Count = 0 Then MsgBox «В папке «» & myPath & «» файлов нет» Exit Sub End If ‘Записываем имена файлов в первый столбец активного листа For Each myFile In myFolder.Files i = i + 1 Cells(i, 1) = myFile.Name Next End Sub |
Ранняя привязка позволяет использовать подсказки свойств и методов объектов при написании кода VBA Excel.
Как получить список папок до 3 уровней вложенности, смотрите в статье VBA Excel. Список папок.
Фразы для контекстного поиска: обход файлов.
Listing filenames in a worksheet, printing all the files to PDF, or making changes to every file in a folder, there are many reasons why we may want to loop through files in a folder. VBA provides us with a few ways to achieve it (1) Dir function (2) File System Object.
Let’s briefly look at each of these before we start looking at the code to loop through files.
Using the Dir Function
The Dir function is a built-in VBA function, meaning it works with Excel, PowerPoint and Word; In fact, it will work anywhere where VBA is available.
The Dir function is easy to use and does not require any special actions to enable it within the Visual Basic Editor.
Using the File System Object (FSO)
The File System Object (FSO) is a separate library of actions that we can enable to use within our VBA code. There are two ways to turn on the FSO library, known as Early or Late Binding. If you’re not sure which to use, then I recommend using Late Binding. It may result in slower code, but it should run with less errors.
Early Binding
Early Binding opens the FSO library as soon as the workbook opens. For this, we need to reference the FSO library in the file.
In the Visual Basic Editor, click Tools > References…
From the References – VBAProject window select the Microsoft Scripting Runtime option, then click OK.
Late Binding
Late Binding does not require any specific actions to enable the FSO Library. We reference the library when we need it within the VBA code.
Examples
The example macros below cover two scenarios
- Looping through all files in a folder
- Looping through all files in a folder and it’s subfolders
Each of these scenarios will use the Dir, Late Binding FSO and Early Binding FSO options.
Looping through all the files in a folder
The example we are looking at prints the file name to the immediate window. But it is easy enough to change the code to make it more complex and fit with your specific circumstances. Check out the other VBA Code Snippets to see what else could be achieved.
Using the Dir Function – Method #1
Sub LoopAllFilesInAFolder() 'Loop through all files in a folder Dim fileName As Variant fileName = Dir("C:UsersmarksDocuments") While fileName <> "" 'Insert the actions to be performed on each file 'This example will print the file name to the immediate window Debug.Print fileName 'Set the fileName to the next file fileName = Dir Wend End Sub
The code above can easily be adapted with the use of wildcard characters. Only the files matching the pattern set by the wildcard characters are included in the scope of the loop.
Example wildcard codes:
'Loop through each file with an extension of ".xlsx"
fileName = Dir("C:UsersmarksDocuments*.xlsx")
'Loop through each file containing the word "January" in the filename
fileName = Dir("C:UsersmarksDocuments*January*")
'Loop through each text file in a folder
fileName = Dir("C:UsersmarksDocuments*.txt")
Using the File System Object (FSO) Late Binding – Method #2
Sub LoopAllFilesInFolder() Dim folderName As String Dim FSOLibrary As Object Dim FSOFolder As Object Dim FSOFile As Object 'Set the file name to a variable folderName = "C:UsersmarksDocuments" 'Set all the references to the FSO Library Set FSOLibrary = CreateObject("Scripting.FileSystemObject") Set FSOFolder = FSOLibrary.GetFolder(folderName) 'Use For Each loop to loop through each file in the folder For Each FSOFile In FSOFolder.Files 'Insert actions to be perfomed on each file 'This example will print the file name to the immediate window Debug.Print FSOFile.Name Next 'Release the memory Set FSOLibrary = Nothing Set FSOFolder = Nothing End Sub
Using File System Object (FSO) Early Binding – Method #3
To use this method, remember to turn on the FSO Library as noted above. Most of the code is the same as Method #2, but for the sake of the copy and pasters out there, I’ll show the full code.
Sub LoopFilesInFolder() Dim folderName As String Dim FSOLibrary As FileSystemObject Dim FSOFolder As Object Dim FSOFile As Object 'Set the file name to a variable folderName = "C:UsersmarksDocuments" 'Set all the references to the FSO Library Set FSOLibrary = New FileSystemObject Set FSOFolder = FSOLibrary.GetFolder(folderName) 'Use For Each loop to loop through each file in the folder For Each FSOFile In FSOFolder.Files 'Insert actions to be perfomed on each file 'This example will print the file name to the immediate window Debug.Print FSOFile.Name Next 'Release the memory Set FSOLibrary = Nothing Set FSOFolder = Nothing End Sub
Looping through all the files in subfolders
Whenever files are stored in subfolders life becomes a little trickier. We now need to find a way to drill down into those subfolders. We will use the same Dir and FSO methods presented above. To ensure the codes work with any number of subfolders, the macro will actually call itself (a technique known as recursion).
Using the DIR function – Method #1
This example prints the full file path (folder path and file name) to the immediate window.
Run the following macro:
Sub loopAllSubFolderSelectStartDirectory() 'Another Macro must call LoopAllSubFolders Macro to start to procedure Call LoopAllSubFolders("C:UsersmarksDocuments") End Sub
Don’t run the following macro, it will be called from the macro above:
'List all files in sub folders Sub LoopAllSubFolders(ByVal folderPath As String) Dim fileName As String Dim fullFilePath As String Dim numFolders As Long Dim folders() As String Dim i As Long If Right(folderPath, 1) <> "" Then folderPath = folderPath & "" fileName = Dir(folderPath & "*.*", vbDirectory) While Len(fileName) <> 0 If Left(fileName, 1) <> "." Then fullFilePath = folderPath & fileName If (GetAttr(fullFilePath) And vbDirectory) = vbDirectory Then ReDim Preserve folders(0 To numFolders) As String folders(numFolders) = fullFilePath numFolders = numFolders + 1 Else 'Insert the actions to be performed on each file 'This example will print the full file path to the immediate window Debug.Print folderPath & fileName End If End If fileName = Dir() Wend For i = 0 To numFolders - 1 LoopAllSubFolders folders(i) Next i End Sub
Using File System Object (FSO) Late Binding – Method #2
Run the following macro:
Sub loopAllSubFolderSelectStartDirectory() Dim FSOLibrary As Object Dim FSOFolder As Object Dim folderName As String 'Set the folder name to a variable folderName = "C:UsersmarksDocuments" 'Set the reference to the FSO Library Set FSOLibrary = CreateObject("Scripting.FileSystemObject") 'Another Macro must call LoopAllSubFolders Macro to start LoopAllSubFolders FSOLibrary.GetFolder(folderName) End Sub
Don’t run the following macro, it will be called from the macro above
Sub LoopAllSubFolders(FSOFolder As Object) Dim FSOSubFolder As Object Dim FSOFile As Object 'For each subfolder call the macro For Each FSOSubFolder In FSOFolder.subfolders LoopAllSubFolders FSOSubFolder Next 'For each file, print the name For Each FSOFile In FSOFolder.Files 'Insert the actions to be performed on each file 'This example will print the full file path to the immediate window Debug.Print FSOFile.Path Next End Sub
Using File System Object (FSO) Early Binding – Method #3
To use this method, remember to turn on the FSO Library as noted above. Most of the code here is the same as method 2, but I will show it in full, so you can copy and paste.
Run the following macro:
Sub loopAllSubFolderSelectStartDirectory() Dim FSOLibrary As FileSystemObject Dim FSOFolder As Object Dim folderName As String 'Set the folder name to a variable folderName = "C:UsersmarksOneDriveDocuments" 'Set the reference to the FSO Library Set FSOLibrary = New FileSystemObject 'Another Macro must call LoopAllSubFolders Macro to start LoopAllSubFolders FSOLibrary.GetFolder(folderName) End Sub
Don’t run the following macro, it will be called from the macro above:
Sub LoopAllSubFolders(FSOFolder As Object) Dim FSOSubFolder As Object Dim FSOFile As Object 'For each subfolder call the macro For Each FSOSubFolder In FSOFolder.subfolders LoopAllSubFolders FSOSubFolder Next 'For each file, print the name For Each FSOFile In FSOFolder.Files 'Insert the actions to be performed on each file 'This example will print the full file path to the immediate window Debug.Print FSOFile.Path Next End Sub
Conclusion
In this post, we have seen 6 methods to loop through files in a folder with VBA.
The Dir function methods are native to VBA and do not require any additional libraries. But the FSO methods require either early or late binding to ensure they run correctly.
About the author
Hey, I’m Mark, and I run Excel Off The Grid.
My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.
In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).
Do you need help adapting this post to your needs?
I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.
But, if you’re still struggling you should:
- Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
- Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
- Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise. List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
- Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.
What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid. Check out the latest posts:
In this article, we are going to learn about how to list the files from folders. Here we will also learn how to list files from subfolders as well. By using File System Object, we can get the list of all Files inside a folder. An important thing to note here is that File System Object can list only files inside a folder. That means, there can be two scenarios here:
Scenario 1: User wants to list all files from the parent folder only. In this case, all the sub-folders inside the parent folder will be ignored.
Scenario 2: User wants to list of all files in parent folder and their sub-folders.
Let’s take a look in both the scenarios one by one.
User wants to get the list of All files inside a folder
User wants to get the list of all files inside a folder as well as Sub-folders
Free Download – File Manager in Excel
i) VBA code to List all files within a Folder Only
Copy and Paste the below Code and this will list down the list of all the files inside the folder. This will list down all the files only in the specified folder. If there are other files that are there in some other Sub-folders.
Sub GetFilesInFolder(SourceFolderName As String)
'--- For Example:Folder Name= "D:Folder Name"
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.folder, SubFolder As Scripting.folder
Dim FileItem As Scripting.File
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'--- This is for displaying, wherever you want can be configured
r = 14
For Each FileItem In SourceFolder.Files
Cells(r, 2).Formula = r - 13
Cells(r, 3).Formula = FileItem.Name
Cells(r, 4).Formula = FileItem.Path
Cells(r, 5).Formula = FileItem.Size
Cells(r, 6).Formula = FileItem.Type
Cells(r, 7).Formula = FileItem.DateLastModified
Cells(r, 8).Formula = "=HYPERLINK(""" & FileItem.Path & """,""" & "Click Here to Open" & """)"
r = r + 1 ' next row number
Next FileItem
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
ii) VBA code to List all files within a Folder and sub-folders as well
Copy and Paste the below Code and this will list down the list of all the files inside the folder as well as sub-folders. If there are other files that are there in some other Sub-folders then it will list down all files from each and Every Folder and Sub-folders.
Sub GetFilesInFolder(SourceFolderName As String, Subfolders As Boolean)
'--- For Example:Folder Name= "D:Folder Name" and Flag as Yes or No
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.folder, SubFolder As Scripting.folder
Dim FileItem As Scripting.File
'Dim r As Long
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'--- This is for displaying, wherever you want can be configured
r = 14
For Each FileItem In SourceFolder.Files
Cells(r, 2).Formula = r - 13
Cells(r, 3).Formula = FileItem.Name
Cells(r, 4).Formula = FileItem.Path
Cells(r, 5).Formula = FileItem.Size
Cells(r, 6).Formula = FileItem.Type
Cells(r, 7).Formula = FileItem.DateLastModified
Cells(r, 8).Formula = "=HYPERLINK(""" & FileItem.Path & """,""" & "Click Here to Open" & """)"
r = r + 1 ' next row number
Next FileItem
'--- This is the Function to go each and Every Folder and get the Files. This is a Nested-Function Calling.
If Subfolders = True Then
For Each SubFolder In SourceFolder.Subfolders
ListFilesInFolder SubFolder.Path, True
Next SubFolder
End If
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub