VBA Loop Through Files in Folder

There are a few ways you can loop through files in a folder. You can do it only for a chosen folder without entering the folders inside it, or you can do it recursively and then save them to a text file.

I created a few examples, where you can see different examples and choose the one you need.

This is the treeview of directories and files.

Loop through files in a folder

This example is the most simple one. It will list all files and folders that are located in the chosen directory.

This code will return the list of files in D:\mydir\.

“pic1.jpg”

“pic2.jpg”

“pic3.jpg”

“text.txt”

Loop through a folder and display files and directories

If you want to list also directories, you have to add an additional parameter to the Dir function, namely vbDirectory.

Change the following line fileName = Dir(“D:\mydir\”) to fileName = Dir(“D:\mydir\”, vbDirectory)

Now, the code will return the following list.

“data”

“pic1.jpg”

“pic2.jpg”

“pic3.jpg”

“text”

“text.txt”

Loop through files recursively

Tomasz Decker is an Excel specialist, skilled in data analysis and financial modeling.

Posted in vba