递归访问文件夹内的子文件夹文件 [英] Recursively access subfolder files inside a folder

查看:105
本文介绍了递归访问文件夹内的子文件夹文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已编写此代码来访问文件夹中的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

这篇关于递归访问文件夹内的子文件夹文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆