XL: Macro to Place Filenames in Given Directory on Worksheet (74493)



The information in this article applies to:

  • Microsoft Excel 2000
  • Microsoft Excel 2002
  • Microsoft Excel 97 for Windows

This article was previously published under Q74493

SUMMARY

The sample macros in this article place the names of all specified file types (specified by file name extension, for example .XLS) for a specified directory into a column on a worksheet.

MORE INFORMATION

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements. Before you run these macros, open a new worksheet and select the cell of the range into which you want the file names to be placed.

To list different file types, you must modify the sample macros by changing the argument in the Dir() function. To return all Microsoft Excel add-in macros, replace "*.XLS" with "*.XLA," and so on. The specified directory can be any valid directory. To search a different folder, change <ExcelFiles> to the folder containing your Excel workbook files.
  1. In a new a module sheet, type the following:
          Sub ListFiles()
             F = Dir("C:\<ExcelFiles>\*.XLS")
             Do While Len(F) > 0
                   ActiveCell.Formula = F
                   ActiveCell.Offset(1, 0).Select
                   F = Dir()
              Loop
          End Sub
    					
  2. To run the macro, open a new worksheet. Select cell A1.
  3. On the Tools menu, point to Macro, and then click Macros. In the list of available macros, select the ListFiles macro, and then click Run.
All workbook files located in the <ExcelFiles> directory will be listed in column A in the worksheet.

To modify the macro so that it returns the file names in a row rather than in a column, change this line
   ActiveCell.Offset(1, 0).Select
				
to this:
   ActiveCell.Offset(0, 1).Select
				

Modification Type:MajorLast Reviewed:6/23/2005
Keywords:kbcode kbhowto kbmacro KB74493