一、递归
'===递归遍历指定文件夹及它所有子文件夹===已知文件名开头几个字母,求文件全路径=====================================
Function GetRecurFile(sFolder_Path As String, sKeyword As String)
Dim oFSO As Object, oSelFolder As Object, oFile As Object, oSubFolder As Object
Dim sA As String, sAA As String
Dim arrA As Variant
Set oFSO = CreateObject("Scripting.FileSystemObject")
sA = ""
'--First Time / traverse the Current folder-------
For Each oFile In oFSO.GetFolder(sFolder_Path).Files
If Left(oFile.Name, Len(sKeyword)) = sKeyword Then
sA = oFile.Path
Exit For
End If
Next oFile
'--------------------------------------------------
If sA = "" Then
'!!!!! Recure Sub-Folder to get the Full-name of file !!!!!!!!
For Each oSubFolder In oFSO.GetFolder(sFolder_Path).SubFolders
sAA = GetRecurFile(oSubFolder.Path, sKeyword) 'RECURE
arrA = Split(sAA, "\")
If sAA <> "" Then
If Left(arrA(UBound(arrA)), Len(sKeyword)) = sKeyword Then
sA = sAA
Exit For
End If
End If
Next oSubFolder
'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
End If
Set oSubFolder = Nothing
Set oFile = Nothing
Set oFSO = Nothing
GetRecurFile = sA
End Function
Sub Try_GetRecurFile() '实例:取得当前工作簿相同路径下,以222开头的第一个文件的全路径
MsgBox GetRecurFile(ThisWorkbook.Path, "222")
End Sub
'=====================================================================
'===递归遍历指定文件夹及它所有子文件夹===已知文件名开头几个字母,求文件全路径=====================================
Function GetRecurFile(sFolder_Path As String, sKeyword As String)
Dim oFSO As Object, oSelFolder As Object, oFile As Object, oSubFolder As Object
Dim sA As String, sAA As String
Dim arrA As Variant
Set oFSO = CreateObject("Scripting.FileSystemObject")
sA = ""
'--First Time / traverse the Current folder-------
For Each oFile In oFSO.GetFolder(sFolder_Path).Files
If Left(oFile.Name, Len(sKeyword)) = sKeyword Then
sA = oFile.Path
Exit For
End If
Next oFile
'--------------------------------------------------
If sA = "" Then
'!!!!! Recure Sub-Folder to get the Full-name of file !!!!!!!!
For Each oSubFolder In oFSO.GetFolder(sFolder_Path).SubFolders
sAA = GetRecurFile(oSubFolder.Path, sKeyword) 'RECURE
arrA = Split(sAA, "\")
If sAA <> "" Then
If Left(arrA(UBound(arrA)), Len(sKeyword)) = sKeyword Then
sA = sAA
Exit For
End If
End If
Next oSubFolder
'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
End If
Set oSubFolder = Nothing
Set oFile = Nothing
Set oFSO = Nothing
GetRecurFile = sA
End Function
Sub Try_GetRecurFile() '实例:取得当前工作簿相同路径下,以222开头的第一个文件的全路径
MsgBox GetRecurFile(ThisWorkbook.Path, "222")
End Sub
'=====================================================================


逍遥枫
