TroyBarnes17
New Member
- Joined
- Jun 13, 2021
- Messages
- 12
- Office Version
- 365
- Platform
- Windows
Hi folks,
I have a folder full of subfolders, each subfolder containing one or more files. I want to perform an operation on each of these files. To do this, I am trying to use this code, but am having trouble understanding the code to make it do what I want. I need to pass each individual file from the subfolders to perform the operation I want on it, then move to the next subfolder and the files within it. May I please ask for help with this?
The code is as follows:
I have a folder full of subfolders, each subfolder containing one or more files. I want to perform an operation on each of these files. To do this, I am trying to use this code, but am having trouble understanding the code to make it do what I want. I need to pass each individual file from the subfolders to perform the operation I want on it, then move to the next subfolder and the files within it. May I please ask for help with this?
The code is as follows:
VBA Code:
Private Function List_Folders_and_Files(folderPath As String, destCell As Range) As Long
Dim FSO As Object, FSfolder As Object, FSsubfolder As Object, FSfile As Object
Dim folders As Collection, levels As Collection, subfoldersColl As Collection
Dim n As Long, c As Long, i As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
Set folders = New Collection
Set levels = New Collection
folders.Add FSO.GetFolder(folderPath)
levels.Add 0
n = 0
Do While folders.Count > 0
'Remove next folder from top of stack
Set FSfolder = folders(folders.Count): folders.Remove folders.Count
c = levels(levels.Count): levels.Remove levels.Count
'Output this folder and its files
destCell.Offset(n, c).Value = "'" & FSfolder.Name
n = n + 1
c = c + 1
For Each FSfile In FSfolder.Files
destCell.Offset(n, c).Value = "'" & FSfile.Name
n = n + 1
Next
'Get collection of subfolders in this folder
Set subfoldersColl = New Collection
For Each FSsubfolder In FSfolder.SubFolders
subfoldersColl.Add FSsubfolder
Next
'Loop through collection in reverse order and put each subfolder on top of stack. As a result, the subfolders are processed and
'output in the correct ascending ASCII order
For i = subfoldersColl.Count To 1 Step -1
If folders.Count = 0 Then
folders.Add subfoldersColl(i)
levels.Add c
Else
folders.Add subfoldersColl(i), , , folders.Count
levels.Add c, , , levels.Count
End If
Next
Set subfoldersColl = Nothing
Loop
List_Folders_and_Files = n
End Function