List files of certain pattern using Excel VBA

南楼画角 提交于 2019-12-02 05:17:37

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

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, e.g. 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

Joe Mako

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!