查看: 25  |  回复: 0
  VBA代码 遍历文件及文件夹
楼主
发表于 2025年3月18日 14:16
Option Explicit

Private Function filelist(folderspec, Optional pstr = "*")
    '遍历某文件夹下的文件,pstr用通配符指定筛选条件
    Dim fs, f, f1, fc, i, arr
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    ReDim arr(1 To fc.Count)
    For Each f1 In fc
        If f1.Name Like pstr Then
            i = i + 1
            arr(i) = f1.Name
        End If
    Next
    ReDim Preserve arr(1 To i)
    filelist = arr
End Function

Private Sub ShowFolderList(folderspec)    '遍历文件夹
    Dim fs, f, f1, s, sf
    Dim hs, h, h1, hf
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set sf = f.SubFolders
    For Each f1 In sf
        List1.AddItem folderspec & "\" & f1.Name
        Call ShowFolderList(folderspec & "\" & f1.Name)
    Next
End Sub

Public Function PickFolder()
    '** 使用FileDialog对象来选择文件夹
    Dim fd As FileDialog
    Dim strPath As String

    Set fd = Application.FileDialog(msoFileDialogFolderPicker)

    '** 显示选择文件夹对话框
    If fd.Show = -1 Then    '** 用户选择了文件夹
        strPath = fd.SelectedItems(1)
    Else
        strPath = ""
    End If
    PickFolder = strPath
    Set fd = Nothing
End Function

Sub SosuoFile(MyPath As String)    '遍历某文件夹及子文件夹中的所有文件
    Dim Myname As String
    Dim a As String
    Dim B() As String
    Dim dir_i() As String
    Dim i, idir As Long
    If Right(MyPath, 1) <> "\" Then MyPath = MyPath + "\"
    Myname = Dir(MyPath, vbDirectory Or vbHidden Or vbNormal Or vbReadOnly)
    Do While Myname <> ""
        If Myname <> "." And Myname <> ".." Then
            If (GetAttr(MyPath & Myname) And vbDirectory) = vbDirectory Then    '如果找到的是目录
                idir = idir + 1
                ReDim Preserve dir_i(idir) As String
                dir_i(idir - 1) = Myname
            Else
                List1.AddItem MyPath & Myname    '把找到的文件显示到列表框中
            End If
        End If
        Myname = Dir    '搜索下一项
    Loop
    For i = 0 To idir - 1
        Call SosuoFile(MyPath + dir_i(i))
    Next i
    ReDim dir_i(0) As String
End Sub

'附:
'在这里可以处理目录中的文件
'Fn.Name       '得到文件名
'Fn.Size       '得到文件大小
'Fn.Path       '得到文件路径
'Fn.Type       '得到文件类型
'Fn.DateLastModified       '得到文件最后的修改日期
'调用方法
'ShowFolderList ("c:\a") 查找目录
'Showfilelist ("c:\a") 查找文件
'SosuoFile ("c:\a") 查找目录+文件


您需要登录后才可以回帖 登录 | 立即注册
【本版规则】请勿发表违反国家法律的内容,否则会被冻结账号和删贴。
用户名: 立即注册
密码:
2020-2025 MaNongKu.com