ExcelTip.com
ExcelTip.com
Account Icon Account Icon Account Icon
Google Exceltip.com
JOIN OUR NEWSLETTER
  and receive for joining:
Free eBook Learn More!
Free Excel ADD-IN
Free Weekly Excel Tip
4 e-books in cd-rom
F1 Formulas & Functions
F1 Formulas & Functions
F1 EXCEL
F1 eBook (Spanish)
F1 EXCEL
Financial Statements.xls
 

» List files in a folder with Office 97 or later using VBA in Microsoft Excel
VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions


In Office 97 or later it's easy to get a list of filenames in a folder, optionally included any subfolders:
Function CreateFileList(FileFilter As String, _
    IncludeSubFolder As Boolean) As Variant
' returns the full filename for files matching 
' the filter criteria in the current folder
Dim FileList() As String, FileCount As Long
    CreateFileList = ""
    Erase FileList
    If FileFilter = "" Then FileFilter = "*.*" ' all files
    With Application.FileSearch
        .NewSearch
        .LookIn = CurDir
        .FileName = FileFilter
        .SearchSubFolders = IncludeSubFolder
        .FileType = msoFileTypeAllFiles
        If .Execute(SortBy:=msoSortByFileName, _
            SortOrder:=msoSortOrderAscending) = 0 Then Exit Function
        ReDim FileList(.FoundFiles.Count)
        For FileCount = 1 To .FoundFiles.Count
            FileList(FileCount) = .FoundFiles(FileCount)
        Next FileCount
        .FileType = msoFileTypeExcelWorkbooks ' reset filetypes
    End With
    CreateFileList = FileList
    Erase FileList
End Function

Sub TestCreateFileList()
Dim FileNamesList As Variant, i As Integer
    'ChDir "C:\My Documents" 
    ' activate the desired startfolder for the filesearch
    FileNamesList = CreateFileList("*.*", False) 
    ' performs the filesearch, includes any subfolders
    ' present the result
    Range("A:A").ClearContents
    For i = 1 To UBound(FileNamesList)
        Cells(i + 1, 1).Formula = FileNamesList(i)
    Next i
End Sub
Rate this tip
12 34 5
  RATING: 3.83
  VIEWS: 29277

READER COMMENTS (view all comments)


No comments have been submitted.


REGISTERED USERS - Click here to post comments


GUESTS (Click here to register)
Name
Comment Title
Comments

Microsoft Word Version 2002 Step By Step (With CD-ROM)

Cashflow Quadrant: Rich Dad's Guide to Financial Freedom

Microsoft Excel 2002 Formulas (With CD-ROM)

Managerial Accounting: Tools for Business Decision Making, WebCT, 2nd Edition

Treason: Liberal Treachery from the Cold War to the War on Terrorism

Microsoft Office XP Introductory Concepts and Techniques

RELATED MICROSOFT EXCEL TIPS


Convert PDF Files to Excel


Excel VBA books
Accounting books
Business Plans
MS Office books
Taxes books

VIEW ALL BOOKS