Ever needed to extract a list of files within a folder/directory? Ever needed to iterate through the files within a given folder/ directory? Below is a simple illustration of how you can do it using the Dir() function. Many examples commonly utilize the FileSystem object, when in reality there is no need to use an external library to do this simple task! As they say Keep It Simple Stupid (the KISS philosophy).
'--------------------------------------------------------------------------------------- ' Procedure : fListDirFiles ' Author : Daniel Pineault, CARDA Consultants Inc. ' Website : http://www.cardaconsultants.com ' Purpose : Return a list of files in a given directory ' Copyright : The following may be altered and reused as you wish so long as the ' copyright notice is left unchanged (including Author, Website and ' Copyright). It may not be sold/resold or reposted on other sites (links ' back to this site are allowed). ' ' Input Variables: ' ~~~~~~~~~~~~~~~~ ' sPath : Full path of folder to examine with trailing \ ' sFilter : specific file extension to limmit search to, leave blank to list all files ' ' Usage: ' ~~~~~~ ' fListDirFiles("C:\Users\Daniel\Documents\") 'List all the files ' fListDirFiles("C:\Users\Daniel\Documents\","xls") 'Only list Excel files ' fListDirFiles("C:\Users\Daniel\Documents\","doc") 'Only list Word files ' ' Revision History: ' Rev Date(yyyy/mm/dd) Description ' ************************************************************************************** ' 1 2012-Jul-13 Initial Release '--------------------------------------------------------------------------------------- Function fListDirFiles(sPath As String, Optional sFilter As String = "*") On Error GoTo Error_Handler Dim sFile As String sFile = Dir(sPath & "*." & sFilter) Do While sFile <> vbNullString If sFile <> "." And sFile <> ".." Then Debug.Print sFile & " was found" 'Do something with the found file End If sFile = Dir 'Loop through the next file that was found Loop Error_Handler_Exit: On Error Resume Next Exit Function Error_Handler: MsgBox "The following error has occured." & vbCrLf & vbCrLf & _ "Error Number: " & Err.Number & vbCrLf & _ "Error Source: fListDirFiles" & vbCrLf & _ "Error Description: " & Err.Description, _ vbCritical, "An Error has Occured!" Resume Error_Handler_Exit End Function |


