VBA使用递归获取文件(对象)



这个想法是检查所有子文件夹中是否存在某个文件。代码查找文件并进行调试。Print打印我的路径,但我的函数"findFile"不返回对象,只返回Nothing。我不认为外部变量是一个好方法,所以我尽量避免这种做法。

Function getFile (ByRef outSourceFolder as Object, ByVal reportName as String) as object
Dim myFile as Object
Set myFile =mylib.findFile(outSourceFolder, reportName) ' always returns Nothing
If Not (myFile Is Nothing) Then
Set getFile = myFile 
End If
End Function
Function findFile(ByRef myFolder As Object, ByVal FileName As String) As Object
Dim iFolder, iFile As Object
For Each iFile In myFolder.Files
If InStr(1, iFile.Name, FileName) Then
Set findFile = iFile
Debug.Print iFile.Path
Exit Function
End If
Next

' recursive call
For Each iFolder In myFolder.SubFolders
Call findFile(iFolder, FileName)
Next
End Function

一个结果递归设置了文件对象,所以我得到了文件,但其余的调用就像是重写了结果。

我已经修复了这个问题:

For Each iFolder In myFolder.SubFolders
Set tFile = findFile(iFolder, FileName)
If Not tFile Is Nothing Then
Set findFile = tFile
Exit Function
End If
Next

所以我没有在需要的时候停止入侵,这是一个问题。

相关内容