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

时间:2013-02-19 05:29:45

标签: vbscript directory

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

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

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

1 个答案:

答案 0 :(得分:17)

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

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