excel-vba get list of Excel files in a folder code example

Example: excel vba get list of Excel files in a folder

'VBA function to return an array of file names from a folder:

Public Function GetFiles(sPath$, Optional sFilter$ = "*.*")
  	Dim p&, f$, s$: s = Space(1e6)        
    f = Dir(sPath & _
        String(Abs(Right(sPath, 1) <> "\"), "\") & sFilter)
        Do While Len(f)
            Mid(s, p + 1, Len(f) + 1) = f & vbLf
            p = p + Len(f) + 1
            f = Dir
        Loop
    GetFiles = Split(Left(s, p - 1), vbLf)
End Function

'--------------------------------------------------------------------

ExcelFiles = GetFiles("C:\temp", "*.xls*")
MsgBox LBound(ExcelFiles)  '<--displays: 0

Tags:

Vb Example