File System Object(FSO对象)B

时间:2021-11-30 01:44:19

一、实例FSO获取当前路径下的文件

 Sub Fsotest()
Dim Fso As New FileSystemObject, Path As String, File
Path = ThisWorkbook.Path & "\"
With Fso
For Each File In .GetFolder(Path).Files '遍历路径下的所有Files
If File.Name <> ThisWorkbook.Name Then
Debug.Print File.Name
End If
Next
End With
End Sub

二、实例FSO遍历当前文件夹所有子文件夹

 Sub test()
Call Getfd(ThisWorkbook.Path & "\")
End Sub Sub Getfd(ByVal Path As String)
Dim Fso As New FileSystemObject
Dim Folder As Variant
For Each Folder In Fso.GetFolder(Path).SubFolders '遍历文件夹
Debug.Print Folder
Getfd (Folder) '递归遍历子文件夹
Next
End Sub

三、实例FSO遍历当前文件夹及子文件夹下的所有Excel文件

 Sub Test()
Call GetFile(ThisWorkbook.Path & "\")
End Sub Sub GetFile(ByVal Path As String)
Dim Fso As New FileSystemObject
Dim Folder As Variant, File As Variant For Each File In Fso.GetFolder(Path).Files '遍历 path路径下文件
If File.Name Like "*.xls*" Then
Debug.Print Path & File
End If
Next For Each Folder In Fso.GetFolder(Path).SubFolders '遍历文件夹
'Debug.Print Folder
GetFile (Folder) '递归遍历子文件夹
Next
End Sub