递归访问文件夹中的子文件夹文件

Pra*_*nks 2 directory vbscript

我写了这段代码来访问文件夹中的Excel文件:

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
Run Code Online (Sandbox Code Playgroud)

现在我必须创建一些子文件夹并在其中放入一些.xls文件.

我应该在我的代码中进行哪些修改来搜索主文件夹和所有其他子文件夹中的文件(子文件夹中还有一些文件夹)?

Ans*_*ers 18

这实际上是一个很好解决的问题.递归意味着您创建了一个自引用函数(一个自我调用的函数).在您的情况下,您将为当前文件夹的每个子文件夹进行函数调用.

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
Run Code Online (Sandbox Code Playgroud)

  • +1简单的6行,但非常有效,感谢不引用搜索引擎.正是这个网站的用途. (2认同)