• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Microsoft Excel Tips and Tricks - Computergaga

  • Home
  • Excel Online Courses
  • Excel Functions List
  • Free Downloads
  • Blog
  • Tutorials
  • About
Home / VBA / Loop Through Subfolders using FileSystemObject

Loop Through Subfolders using FileSystemObject

A common Excel VBA requirement is to work with different files and folders of a directory. It may be that you need to search and open a file, list the names of files from a folder, print all the files from a folder, or even delete files.

The different tasks you may need to perform are endless, but fortunately Excel VBA provides an easy way to access and perform operations on the files and folders of a directory. This easy way is known as FileSystemObject.

To use FileSystemObject, otherwise known as FSO, you first need to create an instance of FileSystemObject. You can then access some of the objects from its model such as File and Folder to perform different tasks.

Macro to Loop Through Subfolders of a Folder

The code below loops through the subfolders of a folder. In this example code, we are looping through the subfolders looking for a particular file called Accounts.xlsx. This is just an example and this macro can be adapted easily to accomplish your own needs.

In this code the file is opened, range A2:F10 is copied into the current file, and then the file is saved and closed. A basic operation to demonstrate the technique of looping through the subfolders in a directory.

Sub LoopSubfoldersAndFiles()
    Dim fso As Object
    Dim folder As Object
    Dim subfolders As Object
    Dim MyFile As String
    Dim wb As Workbook
    Dim CurrFile As Object
With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
End With
   
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder("C:\Users\Trainee1\Desktop\2016\")
    Set subfolders = folder.subfolders
    MyFile = "Accounts.xlsx"
   
    For Each subfolders In subfolders
   
    Set CurrFile = subfolders.Files
       
        For Each CurrFile In CurrFile
            If CurrFile.Name = MyFile Then
                Set wb = Workbooks.Open(subfolders.Path & "\" & MyFile)
                    Range("A2:F10").Copy ThisWorkbook.Sheets(1).Range("A2")
                wb.Close SaveChanges:=True
            End If
        Next
      
    Next
    
    Set fso = Nothing
    Set folder = Nothing
    Set subfolders = Nothing
With Application
    .EnableEvents = True
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With
End Sub

Early in the code the instance of FileSystemObject is created. The Folder and Subfolders variables are then set. The GetFolder method is used for this.

We then have a loop for the subfolders of a folder, and a interior loop for the files within that folder.
The code finishes with the variables being released from memory by setting them to nothing.

More Excel VBA Tutorials

  • Format all instances of certain words in a cell using VBA
  • Hangman game created using Excel VBA
  • Macro to email the Excel workbook as an attachment
  • Export all sheets as PDF using VBA

Reader Interactions

Comments

  1. Craig Papa says

    25 October 2016 at 10:17 am

    Hi, thanks for the code. it works well. but i have a small issue, it stops after the first sub folder within a folder. how would i get it to continue to go into all folders, sub folder and sub sub folders to see if the file exists?

    Reply
    • zhaojun tao says

      30 March 2022 at 3:07 pm

      The code here does not go into the subfolder of sublder,
      I just find the solution here:https://stackoverflow.com/questions/22645347/loop-through-all-subfolders-using-vba

      Reply
  2. Staci says

    22 November 2016 at 11:03 am

    Thanks for the code. I am having trouble incorporating FSO.CopyFile to copy xls files from each subfolder. Any suggestion?

    Reply
    • computergaga says

      26 November 2016 at 9:21 pm

      Problems may be encountered if the file does not exist in a subfolder or already exists in the destination folder.

      Reply
  3. Alwin Selvaraj says

    22 January 2021 at 3:28 pm

    Really helpful. It would be great if you can provide the code to loop through subfolders of subfolder.

    Reply
    • Alan Murray says

      22 January 2021 at 4:49 pm

      Thank you, Alwin. I think I have that code somewhere on my site. I’ll need to dig it out.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Recent Posts

  • Excel SWITCH Function – Nested IF Function Alternative
  • Sum Formulas Only in Excel
  • How to Calculate Age in Excel
  • Custom Sort in Excel
  • Case Sensitive Lookup with XLOOKUP in Excel
Advanced Excel Success book

Footer

Contact

[email protected]

LinkedIn Twitter YouTube

Useful Links

  • Home
  • Excel Online Courses
  • Tutorials
  • Sitemap
  • Privacy Policy
  • Jobs by Jooble

Course Topics

  • Blog
  • Charts
  • Courses
  • Dashboards
  • Downloads
  • Excel Tips
  • Formulas
  • Mail Merge
  • Office
  • PivotTables
  • Power BI
  • Power Pivot
  • Power Query
  • VBA

Join Our Mailing List

© Copyright 2009 Computergaga · All Rights Reserved ·