當前位置:成語大全網 - 新華字典 - VBA中怎麽遍歷所選路徑中所有文件夾及其子文件夾(多個子文件),並返回所有的最底層的文件夾路徑

VBA中怎麽遍歷所選路徑中所有文件夾及其子文件夾(多個子文件),並返回所有的最底層的文件夾路徑

答:執行"獲取所有文件夾",按提示操作。文件夾清單會顯示在工作表的AB列中。

Sub?獲取所有文件夾()

Dim?Directory?As?String

With?Application.FileDialog(msoFileDialogFolderPicker)

.InitialFileName?=?Application.DefaultFilePath?&?"\"

.Title?=?"請選擇壹個文件夾"

.Show

If?.SelectedItems.Count?=?0?Then

Exit?Sub

Else

Directory?=?.SelectedItems(1)

End?If

End?With

Cells.ClearContents

Call?RecursiveDir(Directory)

End?Sub

Public?Sub?RecursiveDir(ByVal?CurrDir?As?String)

Dim?Dirs()?As?String

Dim?NumDirs?As?Long

Dim?Filesize?As?Double

Dim?TotalFolders,?SingleFolder

Cells(1,?1)?=?"目錄名"

Cells(1,?2)?=?"日期/時間"

Range("A1:B1").Font.Bold?=?True

Set?TotalFolders?=?CreateObject("Scripting.FileSystemObject").GetFolder(CurrDir).SubFolders

Cells(WorksheetFunction.CountA(Range("A:A"))?+?1,?1)?=?CurrDir

Cells(WorksheetFunction.CountA(Range("B:B"))?+?1,?2)?=?FileDateTime(CurrDir)

If?TotalFolders.Count?<>?0?Then

For?Each?SingleFolder?In?TotalFolders

ReDim?Preserve?Dirs(0?To?NumDirs)?As?String

Dirs(NumDirs)?=?SingleFolder

NumDirs?=?NumDirs?+?1

Next

End?If

For?i?=?0?To?NumDirs?-?1

RecursiveDir?Dirs(i)

Next?i

End?Sub