一旦在VBA中找到该文件,如何停止递归搜索

时间:2014-01-31 18:06:16

标签: vba access-vba

我有以下脚本,请从此http://www.vbforums.com/showthread.php?613400-Loop-through-folders-subfolders

进行修改
Private Sub Command1_Click()

Dim fld As Folder
Dim searchString As String
Dim ResultFilePath As String
Set fso = New FileSystemObject
Set fld = fso.GetFolder("C:\Users\janedoe\Desktop\jane")   
searchString = "ClaimSheet.xlsx"                       

ResultFilePath = RecursiveSearch(fld, searchString)    
Set fld = Nothing
Set fso = Nothing

If ResultFilePath = "" Then
    MsgBox ("We could not find the file " & searchString)
Else
    MsgBox ("We found it, its at " & ResultFilePath)
End If

End Sub

Function RecursiveSearch(fld As Folder, search As String) As String
Dim tfold As Folder
Dim tfil As File

For Each tfold In fld.SubFolders
    Debug.Print "looking in the  " & tfold & " folder"
    RecursiveSearch tfold, search

    If RecursiveSearch = search Then
        Exit Function
    End If

Next


Debug.Assert InStr(tfil, search) = 0

    If InStr(tfil.Name, search) Then           

        RecursiveSearch = tfil.Path
        Exit function
    End If
Next


End Function

我希望RecursiveSearch函数做的是,搜索文件夹中的searchString文件,找到后,停止搜索并返回文件路径。

问题是,我不能在不丢失行

的值的情况下退出函数
RecursiveSearch = tfil.Path

我认为这样做是因为在返回上一级时函数可能已超出范围。

任何帮助将不胜感激,

1 个答案:

答案 0 :(得分:2)

您的递归行应为:

RecursiveSearch = RecursiveSearch(tfold, search)

这将允许递归的每个级别将其结果传递回链。

此外,您的问题中的代码似乎缺少以下行:

For Each tfil In fld.Files