I have searched the forum, and found similar questions that got answered, but I am really a beginner in VBA.
I want to copy the name, path, and last modified date information to an Excel spreadsheet.
The code in the following two threads can help me add the name, path and last modified date information of a certain folder to Spreadsheet. The only thing I need to do is to add a loop that searches files under subfolders. I tried to, but it was not successful.
Can anyone help me add a loop of the files in the subfolders based on the code below?
Getting file last modified date (explorer value not cmd value)
Excel VBA using FileSystemObject to list file last date modified
Sub ListFilesinFolderNew()
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.Folder
Dim FileItem As Scripting.File
Dim fsoFol As Scripting.Folder
SourceFolderName = "C:\Users\lc\Downloads"
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
Range("A1:C1") = Array("file", "path", "Date Last Modified")
i = 2
For Each fsoFol In SourceFolder.SubFolders
For Each FileItem In fsoFol.Files
Cells(i, 1) = FileItem.Name
Cells(i, 2) = FileItem
Cells(i, 3) = FileItem.DateLastModified
i = i + 1
Next FileItem
Next fsoFol
Set FSO = Nothing
End Sub
Thank you.
In order to list all files in a folder and its subfolders, i would suggest seperating the listing logic into a seperate
Sub
and calling it recursively.Something like this
Alternate method using Dir
Ok try this to get the files on the folder and sub folders:
Or you can do a separate loop for it before you loop on the subfolders.
Just utilize the available properties like ParentFolder.
To check if there are still sub folders undet it, you can use:
Not really ideal but should work. HTH.