Recursive Directory Regex File Search
Sub FindPatternMatchedFiles() Dim objFSO As Object Set objFSO = CreateObject("Scripting.FileSystemObject") Dim objRegExp As Object Set objRegExp = CreateObject("VBScript.RegExp") objRegExp.pattern = ".*xlsx" objRegExp.IgnoreCase = True Dim colFiles As Collection Set colFiles = New Collection RecursiveFileSearch "C:\Path\To\Your\Directory", objRegExp, colFiles, objFSO For Each f In colFiles Debug.Print (f) 'Insert code here to do something with the matched files Next 'Garbage Collection Set objFSO = Nothing Set objRegExp = Nothing End Sub Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _ ByRef matchedFiles As Collection, ByRef objFSO As Object) Dim objFolder As Object Dim objFile As Object Dim objSubFolders As Object 'Get the folder object associated with the target directory Set objFolder = objFSO.GetFolder(targetFolder) 'Loop through the files current folder For Each objFile In objFolder.files If objRegExp.test(objFile) Then matchedFiles.Add (objFile) End If Next 'Loop through the each of the sub folders recursively Set objSubFolders = objFolder.Subfolders For Each objSubfolder In objSubFolders RecursiveFileSearch objSubfolder, objRegExp, matchedFiles, objFSO Next 'Garbage Collection Set objFolder = Nothing Set objFile = Nothing Set objSubFolders = Nothing End Sub
Related Articles:
- Merging Multiple Workbooks Together by Searching Directories and Sub-Folders
- Compact and Repair Access Databases by Searching Directories and Sub-Folders