递归访问文件夹内的子文件夹文件
问题描述:
我已编写此代码来访问文件夹中的Excel文件:
I have written this code to access Excel files inside a folder:
strPath="C:\Test\"
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder (strPath)
Set objExcel= CreateObject("Excel.Application")
objExcel.Visible= False
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.Path) = "xls" Then
现在,我必须创建一些子文件夹并在其中放置一些.xls文件。
Now I have to create some subfolders and put some .xls files in those.
我应该对我的代码进行哪些修改以搜索主文件夹和所有其他子文件夹(子文件夹中也有一些文件夹)中的文件?
What modification should I do in my code for searching files in main folder and all other subfolders (there are also some folders inside subfolders)?
答
这实际上是一个已解决的问题。递归意味着您创建了一个自引用函数(一个自我调用的函数)。在您的情况下,您可以使函数针对当前文件夹的每个子文件夹进行调用。
This is actually a well-solved problem. Recursion means that you create a self-referencing function (a function that calls itself). In your case you'd make the function call itself for each subfolder of the current folder.
TraverseFolders objFso.GetFolder(strPath)
Function TraverseFolders(fldr)
' do stuff with the files in fldr here, or ...
For Each sf In fldr.SubFolders
TraverseFolders sf '<- recurse here
Next
' ... do stuff with the files in fldr here.
End Function