EXCEL-VBA:递归遍历文件夹及子文件夹中的文件

时间:2024-11-10 14:50:06
    Const SearchPath = "D:\PDF\"
    
    Dim DicList, FileList, I, FileName(), FilePath()
    Set DicList = CreateObject("")
    Set FileList = CreateObject("")
    
     SearchPath, ""  '初始化目录
    
    '**************遍历所有目录*******************
    I = 0
    Do While I < 
        Key =  '本次要遍历的目录
        NowDic = Dir(Key(I), vbDirectory) '开始查找
        Do While NowDic <> ""
            If (NowDic <> ".") And (NowDic <> "..") Then
                If (GetAttr(Key(I) & NowDic) And vbDirectory) = vbDirectory Then '找到子目录,则添加
                     Key(I) & NowDic & "\", ""
                End If
            End If
            NowDic = Dir() '再找
        Loop
        I = I + 1
    Loop
    '****************************************************
    
    '**************遍历目录中的所有文件*******************
    For Each Key In  '查找所有目录中的文件
       NowFile = Dir(Key & "*.pdf")
       Do While NowFile <> ""
             NowFile, Key 'Add(Key,Item)  =文件名,=目录
            NowFile = Dir()
       Loop
    Next
    FileName() = 
    FilePath() = 
    '****************************************************