VBA 对遍历文件目录,获得里面的文件的操作

Sub Get_SubFolder_Names()    '提取文件夾名稱
    Dim RtFolder, nlFolder
    Dim xrow As Long
    RtFolder = ThisWorkbook.Path & "\"    '这里指定你的根目录
    xrow = 0
    With CreateObject("Scripting.FileSystemObject").GetFolder(RtFolder)
        For Each nlFolder In .subfolders
            ActiveCell.Offset(xrow) = nlFolder.Name
            xrow = xrow + 1
        Next nlFolder
    End With
End Sub
Scripting.FileSystemObject(只获取指定目录下的文件)
Sub kb()
    i = 1
    path1 = ThisWorkbook.Path & "\"    '这里指定你的根目录
    'file1 = Dir(path1 & "*.xlsm")
    file1 = Dir(path1 & "")
    Do While file1 <> ""
        Cells(i, 1) = file1
        i = i + 1
        file1 = Dir
    Loop
End Sub
Dir遍历(只获取指定目录下得文件)
Public Sub FindFile(mPath As String, Optional sFile As String = "")

    Dim s As String, sDir() As String
    Dim i As Long, d As Long, morder$, csvFile$
    Set dic = CreateObject("scripting.dictionary")
    If Right(mPath, 1) <> "\" Then
        mPath = mPath & "\"
    End If
    '查找目录下的文件
    s = Dir(mPath & sFile, vbArchive + vbDirectory + vbNormal + vbReadOnly)
    Do While s <> ""
    
        If InStr(s, ".xlsx") > 0 Then
            dic(mPath & s) = getit(mPath & s)
        End If
           
       s = Dir
    Loop
    '查找目录下的子目录
    s = Dir(mPath, vbArchive + vbDirectory + vbNormal + vbReadOnly)
    Do While s <> ""
        If s <> "." And s <> ".." Then
            If (GetAttr(mPath & s) And vbDirectory) = vbDirectory Then
            d = d + 1
            ReDim Preserve sDir(d)
            sDir(d) = mPath & s
            End If
        End If
        s = Dir
    Loop
    
    '开始递归
    For i = 1 To d
        FindFile sDir(d) & "\"
    Next

End Sub
Dir 获取指定目录下递归得到所有文件包括子文件夹

 

posted on 2013-12-08 13:59  鱼东鱼  阅读(1274)  评论(1编辑  收藏  举报

导航