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

问题描述 投票:0回答:2

我编写了这段代码来访问文件夹内的 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 文件。

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

vbscript directory
2个回答
19
投票

这其实是一个很好解决的问题。递归意味着您创建一个自引用函数(调用自身的函数)。在您的情况下,您可以为当前文件夹的每个子文件夹调用函数本身。

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

-5
投票

在脚本开始时运行此命令,它将列出所有文件夹中的所有文件:

dir /S/B > AllFoldersAndFiles.txt

然后循环遍历文件列表。这对我有用。

递归 vb 有点棘手。

© www.soinside.com 2019 - 2024. All rights reserved.