Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
942 views
in Technique[技术] by (71.8m points)

vbscript - Recursively access subfolder files inside a folder

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

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)?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...