EXCEL-VBA:遞迴遍歷資料夾及子資料夾中的檔案
阿新 • • 發佈:2019-01-09
Const SearchPath = "D:\PDF\" Dim DicList, FileList, I, FileName(), FilePath() Set DicList = CreateObject("Scripting.Dictionary") Set FileList = CreateObject("Scripting.Dictionary") DicList.Add SearchPath, "" '初始化目錄 '**************遍歷所有目錄******************* I = 0 Do While I < DicList.Count Key = DicList.Keys '本次要遍歷的目錄 NowDic = Dir(Key(I), vbDirectory) '開始查詢 Do While NowDic <> "" If (NowDic <> ".") And (NowDic <> "..") Then If (GetAttr(Key(I) & NowDic) And vbDirectory) = vbDirectory Then '找到子目錄,則新增 DicList.Add Key(I) & NowDic & "\", "" End If End If NowDic = Dir() '再找 Loop I = I + 1 Loop '**************************************************** '**************遍歷目錄中的所有檔案******************* For Each Key In DicList.Keys '查詢所有目錄中的檔案 NowFile = Dir(Key & "*.pdf") Do While NowFile <> "" FileList.Add NowFile, Key 'Add(Key,Item) FileList.Key=檔名,FileList.Item=目錄 NowFile = Dir() Loop Next FileName() = FileList.Keys FilePath() = FileList.Items '****************************************************