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
Code:
=======================================================================
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
Rajan.
Bookmarks