Files in a Directory
Below we will look at a program in Excel VBA that loops through all closed workbooks and worksheets in a directory, and displays all the names.
Download Book1.xls, Book2.xls, Book3.xls, Book4.xls and Book5.xls and add them to "C:\test\"
Add the following code lines to the command button:
1. First, we declare two variables of type String, a Worksheet object and two variables of type Integer.
2. To avoid screen flicker, turn off screen updating.
3. Initialize the variable directory. We use the Dir function to find the first *.xl?? file stored in this directory.
fileName = Dir(directory & "*.xl??")
Note: the Dir function supports the use of multiple character (*) and single character (?) wildcards to search for all different type of Excel files.
4. The variable fileName now holds the name of the first Excel file found in the directory. Add a Do While Loop.
Add the following code lines (at 5, 6, 7, 8 and 9) to the loop.
5. Initialize the variables of type Integer and add the name of the Excel file to the first column of row i.
j = 2
Cells(i, 1) = fileName
6. There is no simple way to extract data (or sheet names) from closed Excel files. Therefore, we open the Excel file.
7. Add all the sheet names of the Excel file to the other columns of row i.
Workbooks("files-in-a-directory.xls").Worksheets(1).Cells(i, j).Value = sheet.Name
j = j + 1
8. Close the Excel file.
9. The Dir function is a special function. To get the other Excel files, you can use the Dir function again with no arguments.
Note: when no more file names match, the Dir function returns a zero-length string (""). As a result, Excel VBA will leave the Do While loop.
10. Turn on screen updating again (outside the loop).
11. Test the program.