VBA: Output file list in a directory, recursively


This is the code I frequently use.

It recursively exports file list in a directory on Microsoft Office Application, like Excel. It is written in VBA.

VBA can be written in object oriented way, but I didn’t because I had to write the code as soon as possible.

Process Flow

  1. A user clicks the button on the sheet.
  2. The program show a folder browsing dialog.
  3. User chooses the folder, then the program make the list of file in the folder.
  4. The program exports the file list onto a form (or sheet).

To Do

  • Create a module file and create the following functions.
    • get file list
    • handle folder browsing dialog
  • Create a dialog to show the result.
  • Create a button on the sheet and add function on clicking.

Create a module file of VBA, and add the functions below.

Get file list

getFileAndDirectories is the function to get file list and make output text. Folder and subfolder are separated by “/“, it is the requirement of my circumstance.

Selecting Folder

The above function get the file list in the folder, and we should add the function to decide which folder should be searched.

The following function meets our requirement.

OK, module was created.

Result Output Form

Create a form to show the result.

I created the form, textViewForm, having only one TextBox. Set TextBox property to handle multi-line text.

The result is text data, so it can be printed on sheet.

Now, add button on the sheet and set to start process on clicking.

Add Button

Add a button onto the sheet and add the following code to start process on clicking it.

Be careful for error handling. The above code is not so sophisticated.