PDA

View Full Version : Loop through subfolders



Moreno20
03-11-2014, 12:16 PM
Hello,

I have made a code to search for a certain string inside excel files that are in a cetain folder.
I'm ok untll here but th problem is that I also want to search inside excel files that are also on subfolders inside that first folder.

The code needs to look for the strin on the first excel file:
- If found than stop the macro
- If not found than lmove to next file.
- If not found on any files on the main folder, than start searching on subfolders, and so on.

Thank you

Kenneth Hobs
03-11-2014, 12:46 PM
'http://www.ozgrid.com/forum/showthread.php?t=157939
Sub Test_SearchFiles()
Dim v As Variant, a() As Variant
SearchFiles ThisWorkbook.Path, "*.xls", 0, a(), True
For Each v In a()
Debug.Print v
Next v
End Sub


Private Function SearchFiles(myDir As String _
, myFileName As String, n As Long, myList() _
, Optional SearchSub As Boolean = False) As Variant
Dim fso As Object, myFolder As Object, myFile As Object
Set fso = CreateObject("Scripting.FileSystemObject")
For Each myFile In fso.getfolder(myDir).Files
Select Case myFile.Attributes
Case 2, 4, 6, 34
Case Else
If (Not myFile.Name Like "~$*") _
* (myFile.Path & "\" & myFile.Name <> ThisWorkbook.FullName) _
* (UCase(myFile.Name) Like UCase(myFileName)) Then
n = n + 1
ReDim Preserve myList(1 To 2, 1 To n)
myList(1, n) = myDir
myList(2, n) = myFile.Name
End If
End Select
Next
If SearchSub Then
For Each myFolder In fso.getfolder(myDir).subfolders
SearchFiles = SearchFiles(myFolder.Path, myFileName, _
n, myList, SearchSub)
Next
End If
SearchFiles = IIf(n > 0, myList, CVErr(xlErrRef))
End Function