Hi Guys,
Many times we need to loop through folders , sub folders and files , i have created a code to get the folder structure of a given path
=======================================================================
Public ObjFolder As Object
Many times we need to loop through folders , sub folders and files , i have created a code to get the folder structure of a given path
=======================================================================
Public ObjFolder As Object
Public objFso As Object
Public objFldLoop As
Object
Public lngCounter As Long
Public objFl As Object
'===================================================
'A procedure to call the Function LoopThroughEachFolder(objFolder)
'===================================================
Sub GetFolderStructure()
'
lngCounter = 0
Set objFso =
CreateObject("Scripting.FileSystemObject")
With
Application.FileDialog(msoFileDialogFolderPicker)
.Show
Set ObjFolder =
objFso.GetFolder(.SelectedItems(1))
End With
Range("A1").Offset(lngCounter).Value = ObjFolder.Path
LoopThroughEachFolder
ObjFolder
End Sub
'===================================================
'Function to Loop through each Sub Folders
'===================================================
Function LoopThroughEachFolder(fldFolder As Object)
For Each objFldLoop In
fldFolder.subFolders
lngCounter = lngCounter +
1
Range("A1").Offset(lngCounter).Value = objFldLoop.Path
LoopThroughEachFolder
objFldLoop
Next
End Function
'=================================================== =========
'In below function we have a nested loop to iterate each files also
'=================================================== =========
Function LoopThroughEachFolder1(fldFolder As Object)
For Each objFldLoop In fldFolder.subFolders
lngCounter = lngCounter + 1
Range("A1").Offset(lngCounter).Value = objFldLoop.Path
For Each objFl In objFldLoop.Files
Range("A1").Offset(lngCounter, 1).Value = objFl.Name
lngCounter = lngCounter + 1
Next
LoopThroughEachFolder1 objFldLoop
Next
End Function
2 comments:
How do you define the directory in which you which to search folders/subfolders/files?
I don't see that defined anywhere. Is it the current directory?
@ Mark
It is ObjFolder, declared as a Global ( available everywhere ) variable at the start of a Module.
Public ObjFolder As Object
That is passed in this line by the initial calling procedure, Sub GetFolderStructure()
LoopThroughEachFolder ObjFolder
You may be more familiar with another version of that Call line
Call LoopThroughEachFolder(ObjFolder)
The called Function, ( a recursion type Function ) , takes that Folder and as necessary runs copies of itself ( by virtue of it “Calling itself” ) talking Sub Folders of the taken in Folder at the Line within the Function which “Calls itself”
LoopThroughEachFolder objFldLoop
Which again you might recognise in this alternative form
Call LoopThroughEachFolder(objFldLoop)
Alan Elston
Post a Comment