Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

XL: Macro to Place Filenames in Given Directory on Worksheet


View products that this article applies to.

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.

↑ Back to the top


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
				

↑ Back to the top


Keywords: KB74493, kbmacro, kbhowto, kbcode

↑ Back to the top

Article Info
Article ID : 74493
Revision : 4
Created on : 9/19/2011
Published on : 9/19/2011
Exists online : False
Views : 11