使用 Excel VBA 列出特定模式的文件

发布于 2024-07-14 06:25:00 字数 78 浏览 8 评论 0原文

如何列出用户指定目录中与特定模式匹配的所有文件? 这应该在所选目录的子文件夹内递归地工作。 我还需要一种方便的方式(如树控件)来列出它们。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

此生挚爱伱 2024-07-21 06:25:00

似乎有几个答案讨论了递归,一个答案讨论了正则表达式。 下面是一些将两个主题放在一起的代码。 我从 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

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
玩物 2024-07-21 06:25:00

作为一般指针,请查看 Application.FileSearch、递归函数、用户窗体和“Microsoft TreeView 控件”。

FileSearch 可用于查找与模式匹配的文件夹中的文件,递归函数可以调用自身,直到用尽所有路径,UserForm 可以托管用于显示数据的控件,TreeView 控件可以显示文件系统。

请记住,有一些预构建的函数/控件可用于显示文件系统,例如 Application.GetOpenFileName、Application.GetSaveAsFileName、Microsoft WebBrowser(给定“file://...”URL)。

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

梦里泪两行 2024-07-21 06:25:00

尝试 Windows 脚本 - 文件系统对象。 这个可以从 vba 创建的 COM 对象具有列出目录等功能。

您可以在

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

自由范儿 2024-07-21 06:25:00

不完全是你所要求的,但我想我会把它发布在这里,因为它是相关的。

这是根据 http://www.cpearson.com/excel/FOLDERTREEVIEW 中找到的代码修改的。 ASPX

这需要参考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

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
岁月流歌 2024-07-21 06:25:00

我看到我上面的人已经回答了如何通过文件树递归,这可能会让您对搜索文件/文件名中的模式感兴趣。 它是一个允许使用正则表达式的 VBA 函数。

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

您可以使用它来搜索文件名中的模式。 我建议正则表达式主页了解有关如何使用正则表达式的更多信息

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文