简体   繁体   中英

List files of certain pattern using Excel VBA

How to list all the files which match a certain pattern inside a user specified directory? This should work recursively inside the sub folders of the selected directory. I also need a convenient way(like tree control) of listing them.

It appears that a couple answers talk about recursion, and one about regex. Here's some code that puts the two topics together. I grabbed the code from http://vba-tutorial.com

Sub FindPatternMatchedFiles()

    Dim objFSO As Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    Dim objRegExp As Object
    Set objRegExp = CreateObject("VBScript.RegExp")
    objRegExp.pattern = ".*xlsx"
    objRegExp.IgnoreCase = True

    Dim colFiles As Collection
    Set colFiles = New Collection

    RecursiveFileSearch "C:\Path\To\Your\Directory", objRegExp, colFiles, objFSO

    For Each f In colFiles
        Debug.Print (f)
        'Insert code here to do something with the matched files
    Next

    'Garbage Collection
    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

    'Get the folder object associated with the target directory
    Set objFolder = objFSO.GetFolder(targetFolder)

    'Loop through the files current folder
    For Each objFile In objFolder.files
        If objRegExp.test(objFile) Then
            matchedFiles.Add (objFile)
        End If
    Next

    'Loop through the each of the sub folders recursively
    Set objSubFolders = objFolder.Subfolders
    For Each objSubfolder In objSubFolders
        RecursiveFileSearch objSubfolder, objRegExp, matchedFiles, objFSO
    Next

    'Garbage Collection
    Set objFolder = Nothing
    Set objFile = Nothing
    Set objSubFolders = Nothing

End Sub

Not exactly what you asked for, but I thought I would post this here as it is related.

This is modified from the code found at http://www.cpearson.com/excel/FOLDERTREEVIEW.ASPX

This requires the reference Microsoft Scripting Runtime .

Sub ListFilePaths()

    Dim Path As String
    Dim Files As Long

    Path = "C:\Folder"

    Files = GetFilePaths(Path, "A", 1)

    MsgBox "Found " & Files - 1 & " Files"

End Sub

Function GetFilePaths(Path As String, Column As String, StartRow As Long) As Long

    Dim Folder As Scripting.Folder
    Dim SubFolder As Scripting.Folder
    Dim File As Scripting.File
    Dim FSO As Scripting.FileSystemObject
    Dim CurrentRow As Long

    Set FSO = New Scripting.FileSystemObject
    Set Folder = FSO.GetFolder(folderpath:=Path)

    CurrentRow = StartRow

    For Each File In Folder.Files
        Range(Column & CurrentRow).Value = File.Path
        CurrentRow = CurrentRow + 1
    Next File

    For Each SubFolder In Folder.SubFolders
        CurrentRow = GetFilePaths(SubFolder.Path, Column, CurrentRow)
    Next SubFolder

    GetFilePaths = CurrentRow

    Set Folder = Nothing
    Set FSO = Nothing
End Function

I see that the people above me have already answered how to recurse through the file tree, This might interest you in searching for patterns in the file/file name. It is a Function for VBA that will allow regular expressions to be used.

Private Function RegularExpression(SearchString As String, Pattern As String) As String

    Dim RE As Object, REMatches As Object

    'Create the regex object' 
    Set RE = CreateObject("vbscript.regexp")
    With RE
        .MultiLine = False
        .Global = False
        .IgnoreCase = True
        'set the search pattern using parameter Pattern'
        .Pattern = Pattern 
    End With

    'Search for the pattern' 
    Set REMatches = RE.Execute(SearchString) 
    If REMatches.Count > 0 Then
        'return the first match'
        RegularExpression = REMatches(0) 
    Else
        'nothing found, return empty string'
        RegularExpression = ""
    End If

End Function

You can use this to search the file names for patterns. I suggest regular expressions home for more information on how to use Regular expressions

As a general pointer, take a look at Application.FileSearch, recursive functions, Userforms and the 'Microsoft TreeView Control'.

FileSearch can be used to find files within a folder matching a pattern, a recursive function can call itself until all paths have been exhausted, a UserForm can host controls for displaying your data and the TreeView control can display your file system.

Bear in mind that there are pre-built functions/controls which can be used for displaying file systems, eg Application.GetOpenFileName, Application.GetSaveAsFileName, Microsoft WebBrowser (given a 'file://...' URL).

Try Windows Scripting - File System Objects. This COM object which can be created form vba has functions for listing directories etc.

You can find documentation on MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM