Vba excel file in folder

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!
vba save as

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…

VBA Editor - Tools References

From the References – VBAProject window select the Microsoft Scripting Runtime option, then click OK.

Microsoft Scripting Runtime required for FSO VBA Loop through files in folder

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

  1. Looping through all files in a folder
  2. 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.


Headshot Round

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:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. 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.
  4. 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:

VBA Code to list Files in Folder

Complete Excel VBA Course

To work on multiple files through VBA programming, you need to have VBA code that can list files in a folder.

 Here is a simple code for you, this function list files in a folder on an Excel sheet. Note that if there are sub-folders available in the folder then this function will not read the files inside the sub-folders.

VBA to List File name from Excel Folder

VBA code: List all file names from a folder into a worksheet

'This function lists files in a folder
'Note: It will not read any files inside a sub-folder
Public Sub ListFilesInFolder()
    'Variable Declaration
    Dim strPath As String
    Dim vFile As Variant
    Dim iCurRow As Integer
    'Clear old data
    Sheet1.Range("B9:B1000").ClearContents
    'Set the path of the folder
    strPath = Sheet1.Range("B4").Value
    'Add slash at the end of the path
    If Right(strPath, 1) <> "/" And Right(strPath, 1) <> "" Then
        strPath = strPath & ""
    End If
    'Set Directory to folder path
    ChDir strPath
    vFile = Dir(strPath & "*.*") 'Change or add formats to get specific file types
    iCurRow = 9
    Do While vFile <> "" 'LOOP until all files in folder strPath have been looped through
        Sheet1.Cells(iCurRow, 2).Value = vFile
        vFile = Dir
        iCurRow = iCurRow + 1
    Loop
End Sub

List All File Names from A Folder into Worksheet by Using VBA Code

To use this code in your Excel file, follow below steps:

Complete Excel VBA Course

1. Open an Excel file
2. Press Alt+F11
3. Insert a Module (Insert>Module) from the menu bar
4. Paste the code in the module
5. Now add a shape to the Excel sheet
6. Give a name to the shape like ‘List Files in Folder’
7. Right-click on the shape and select ‘Assign Macro…’

Macro to List File name from Excel Folder

8. Select ‘ListFilesInFolder’ from the list and click on ‘Ok’ button

Macro to List File name from Excel Folder

9. Done, enter a folder path in cell B4 and click on the ‘List Files in Folder’ button

Macro to List File name from Excel Folder

File Manager Tool

Download Practice File

You can also practice this through our practice files. Click on the below link to download the practice file.

Recommended Articles

  • Time and Motion Study-Complete guide
  • VBA to read Excel data using connection string
  • Excel VBA tool to get file properties
  • Excel VBA Tool to create folders
  • VBA Code to re-link MS Access link tables

Excel VBA Course : Beginners to Advanced

We are currently offering our Excel VBA Course at discounted prices. This courses includes On Demand Videos, Practice Assignments, Q&A Support from our Experts. Also after successfully completion of the certification, will share the success with Certificate of Completion

This course is going to help you to excel your skills in Excel VBA with our real time case studies.

Lets get connected and start learning now. Click here to Enroll.

Secrets of Excel Data Visualization: Beginners to Advanced Course

Here is another best rated Excel Charts and Graph Course from excelsirji. This courses also includes On Demand Videos, Practice Assignments, Q&A Support from our Experts.

This Course will enable you to become Excel Data Visualization Expert as it consists many charts preparation method which you will not find over the internet.

So Enroll now to become expert in Excel Data Visualization. Click here to Enroll.

Like this post? Please share to your friends:
  • Vba excel export to excel
  • Vba excel exit from sub
  • Vba excel exit all subs
  • Vba excel evaluate пример
  • Vba excel error codes