从递归文件搜索中省略文件夹

时间:2016-10-30 23:20:21

标签: vba recursion access-vba ms-access-2013

我正在运行递归文件搜索程序,我的计算机已关闭。我知道程序停在哪个目录,有没有办法为递归文件搜索指定一个开始文件夹?例如,假设这是我的结构

R:\
R:\Test\
R:\Test\Folder1\
R:\Test1\
R:\Test1\Folder1\
R:\Test2\
R:\Test2\Folder2\

如果我希望递归搜索从

开始
R:\Test1\Folder1\

程序将如何进行?

Option Compare Database

Sub ScanTablesWriteDataToText()
Dim Fileout As Object
Dim fso As Object
Dim objFSO As Object
Dim accapp As Access.Application
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim colFiles As Collection
Set objFSO = CreateObject("Scripting.FileSystemObject")

Dim objRegExp As Object
Set objRegExp = CreateObject("VBScript.RegExp")
objRegExp.Pattern = ".jpg"
objRegExp.IgnoreCase = True

Set colFiles = New Collection

RecursiveFileSearch "R:\", objRegExp, colFiles, objFSO

For Each f In colFiles
    'do something
Next
Set objFSO = Nothing
Set objRegExp = Nothing

End Sub
Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _
                ByRef matchedFiles As Collection, ByRef objFSO As Object)

Dim objFolder As Object
Dim objFile As Object
Dim objSubFolders As Object
Set objFolder = objFSO.GetFolder(targetFolder)
For Each objFile In objFolder.files
    If objRegExp.test(objFile) Then
        matchedFiles.Add (objFile)
    End If
Next
Set objSubFolders = objFolder.Subfolders
For Each objSubfolder In objSubFolders
    RecursiveFileSearch objSubfolder, objRegExp, matchedFiles, objFSO
Next
Set objFolder = Nothing
Set objFile = Nothing
Set objSubFolders = Nothing

End Sub

2 个答案:

答案 0 :(得分:0)

我改变你的递归子以包含另外两个参数 - 一个用于你试图找到的文件夹,一个布尔值来表示它是否被找到:

Sub RecursiveFileSearch(ByVal targetFolder As String, ByRef objRegExp As Object, _
                ByRef matchedFiles As Collection, ByRef objFSO As Object, _
                ByVal startFolder As String, ByVal found As Boolean)

  Dim objFolder As Object
  Dim objFile As Object
  Dim objSubFolders As Object
  Set objFolder = objFSO.GetFolder(targetFolder)

  If startFolder = "" Or found Then
    For Each objFile In objFolder.files
      If objRegExp.test(objFile) Then
          matchedFiles.Add (objFile)
      End If
    Next
  End If

  Set objSubFolders = objFolder.Subfolders
  For Each objSubFolder In objSubFolders
    If objSubFolder = startFolder Then
      found = True
    End If

    RecursiveFileSearch objSubFolder, objRegExp, matchedFiles, objFSO, _
      startFolder, found
  Next

  Set objFolder = Nothing
  Set objFile = Nothing
  Set objSubFolders = Nothing

End Sub

当你打电话时,它会是:

RecursiveFileSearch "R:\", objRegExp, colFiles, objFSO, "R:\Test1\Folder1\", false

答案 1 :(得分:0)

你可以通过运行(优雅的)PowerShell

来简化这一点

将递归JPG列表转储到C:\temp\filename.csv

Sub Comesfast()
X2 = Shell("powershell.exe get-childitem ""C:\Test1\Folder1"" -recurse | where {$_.extension -eq "".jpg""} | Select-Object FullName| export-csv ""C:\temp\filename.csv"" ", 1)
End Sub