循环浏览文件夹下的所有子文件夹和文件,并将最后修改的date信息写入Excel电子表格中

我search了论坛,发现了类似的问题,但是我真的是VBA的初学者。

我想将名称,path和上次修改date信息复制到Excel电子表格中。

以下两个线程中的代码可以帮助我将某个文件夹的名称,path和上次修改date信息添加到Spreadsheet中。 我唯一需要做的就是添加一个循环来search子文件夹下的文件。 我试过,但没有成功。

任何人都可以帮助我根据下面的代码在子文件夹中添加一个循环的文件?

获取文件上次修改date(资源pipe理器值不是cmd值)

Excel VBA使用FileSystemObject列出文件上次修改date

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 

谢谢。

为了列出文件夹及其子文件夹中的所有文件,我build议将列表逻辑分成单独的Sub并recursion调用。

像这样的东西

 Sub ListFilesinFolderNew() Dim FSO As Scripting.FileSystemObject Dim ws As Worksheet Dim cl As Range Dim SourceFolderName As String SourceFolderName = "C:\Users\lc\Downloads" Set FSO = New Scripting.FileSystemObject Set ws = ActiveSheet '<-- adjust to suit your needs ws.Range("A1:C1") = Array("file", "path", "Date Last Modified") Set cl = ws.Cells(2, 1) ListFolders cl, FSO.GetFolder(SourceFolderName) Set FSO = Nothing End Sub Sub ListFolders(rng As Range, Fol As Scripting.Folder) Dim SubFol As Scripting.Folder Dim FileItem As Scripting.File ' List Files For Each FileItem In Fol.Files rng.Cells(1, 1) = FileItem.Name rng.Cells(1, 2) = FileItem.ParentFolder.Path rng.Cells(1, 3) = FileItem.DateLastModified Set rng = rng.Offset(1, 0) Next ' Proces subfolders For Each SubFol In Fol.SubFolders ListFolders rng, SubFol Next End Sub 

确定试试这个文件夹和子文件夹:

 Dim donewithparent As Boolean For Each fsoFol In SourceFolder.SubFolders If Not donewithparent Then For Each FileItem In fsoFol.ParentFolder.Files Cells(i, 1) = FileItem.Name Cells(i, 2) = FileItem Cells(i, 3) = FileItem.DateLastModified i = i + 1 Next End If donewithparent = True 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 

或者你可以做一个单独的循环,然后再循环子文件夹。
只要使用像ParentFolder可用的属性。
要检查是否仍有子文件夹undet它,您可以使用:

 If fsoFol.Subfolders.Count > 0 Then '~~> add another loop here End If 

不是很理想,但应该工作。 HTH。