从目录和子目录中获取过滤文件名列表到数组中

时间:2019-11-15 19:56:04

标签: excel vba

我在Google上搜索并找到了很多我要找的结果。做了大量的阅读,现在我的头很痛。因此,仅在此站点上就有关于此主题的许多问题,我从2015年开始关注此question。我对其进行了修改,以使其能够与过滤后的结果一起使用,但没有用。它还捕获了整个文件路径和文件名,而不仅仅是文件名。由于我对VBA的了解并不多,所以有些命令是我的头绪。

因此,我找到了这个question,我喜欢这个答案。我可以阅读它,并轻松地大致了解它所发生的情况。问题在于它仅在当前目录中查找。

应该如何修改它以查看子目录并拉出.xls文件名列表?

我想我有一种将其过滤为xls文件的方法,但同时也想知道是否有更好的方法。

这是我基于第二个问题的当前代码:

 System.Net.Http.HttpRequestException: Network subsystem is down ---> System.Net.Sockets.SocketException: Network subsystem is down
  at System.Net.Http.ConnectHelper.ConnectAsync (System.String host, System.Int32 port, System.Threading.CancellationToken cancellationToken) [0x00110] in <c85119bf7e3e421490ae6b5487992fff>:0 

2 个答案:

答案 0 :(得分:1)

尝试一下:

<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <PlatformTarget>AnyCPU</PlatformTarget>
    <RuntimeIdentifier>win7-x64</RuntimeIdentifier>    
    <SignAssembly>true</SignAssembly>
    <AssemblyOriginatorKeyFile>StrongNameKey.snk</AssemblyOriginatorKeyFile>
    <DelaySign>false</DelaySign>
  </PropertyGroup>

用法示例:

'Return a collection of file objects given a starting folder and a file pattern
'  e.g. "*.txt"
'Pass False for last parameter if don't want to check subfolders
Function GetMatches(startFolder As String, filePattern As String, _
                    Optional subFolders As Boolean = True) As Collection

    Dim fso, fldr, f, subFldr
    Dim colFiles As New Collection
    Dim colSub As New Collection

    Set fso = CreateObject("scripting.filesystemobject")

    colSub.Add startFolder

    Do While colSub.Count > 0

        Set fldr = fso.getfolder(colSub(1))
        colSub.Remove 1

        For Each f In fldr.Files
            'check filename pattern
            If UCase(f.Name) Like UCase(filePattern) Then colFiles.Add f
        Next f

        If subFolders Then
            For Each subFldr In fldr.subFolders
                colSub.Add subFldr.Path
            Next subFldr
        End If

    Loop

    Set GetMatches = colFiles

End Function

答案 1 :(得分:0)

使用此:

Sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "D:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
End Sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

来自: Loop Through All Subfolders Using VBA