我有一个子函数调用一个函数来搜索子文件夹,然后返回一个带文件名的文件路径,这样主子函数就可以使用该字符串来创建一个附件。它是一个递归函数,因此它一直在strJDFile中重置我的值。我需要它搜索所有子文件夹,找到我的文件,然后将strJDFile值发送到主子。因为它一直在重置,所以没有任何东西可以通过sub。我究竟做错了什么?否则该功能起作用。这只是让结果得以实现的最后一步。
Function recurse(sPath As String)
Dim FSO As New FileSystemObject
Dim myFolder As Scripting.Folder
Dim mySubFolder As Scripting.Folder
Dim myFile As Scripting.File
Dim strName As String
Dim strJDFile As String
Dim strDir As String
Dim strJDName As String
Set myFolder = FSO.GetFolder(sPath)
strName = Range("a2").Offset(0, 3)
For Each mySubFolder In myFolder.SubFolders
For Each myFile In mySubFolder.Files
If myFile.name Like "*" & strName & "*" Then
strJDName = myFile.name
strDir = mySubFolder & "\"
strJDFile = strDir & strJDName
Exit Function
End If
Next
recurse = recurse(mySubFolder.Path)
Next
End Function
我查看了这个问题的多个帖子,包括这个VBA macro that search for file in multiple subfolders,我在那里提出了答案,但这就是如何设置递归,而不是如何使值传递给sub。问题就像我上面所说的那样,每次碰到下一个'它重置,所以我的strJDFile值设置为""再次。但是你需要在recurse-strDir之后使用Next,以便让它继续运行到下一个子文件夹,直到找到正确的值。我只需要保留值而不是空白。我介绍了F8,这就是我发现当它击中最终的Next时它重置的方式。这就是我添加退出函数的原因,但这也没有用。
答案 0 :(得分:2)
"递归"返回,而不是strJDFile。
Private Sub functionTest()
Dim x As String
Dim fPath As String
fPath = "C:\Test"
x = recurse(fPath)
If x = "" Then x = "No results."
Debug.Print " *** recurse has returned: " & x
Debug.Print "Done"
End Sub
Function recurse(sPath As String)
Dim FSO As New FileSystemObject
Dim myFolder As Scripting.folder
Dim mySubFolder As Scripting.folder
Dim myFile As Scripting.file
Dim strName As String
Dim strJDFile As String
Dim strDir As String
Dim strJDName As String
Set myFolder = FSO.GetFolder(sPath)
' strName = Range("a2").Offset(0, 3)
strName = "test.xlsx"
For Each mySubFolder In myFolder.SubFolders
Debug.Print " mySubFolder: " & mySubFolder
For Each myFile In mySubFolder.Files
If myFile.name Like "*" & strName & "*" Then
strJDName = myFile.name
strDir = mySubFolder & "\"
strJDFile = strDir & strJDName
recurse = strJDFile
Exit Function
Else
Debug.Print " myFile.name: " & myFile.name
End If
Next
recurse = recurse(mySubFolder.path)
Next
End Function