如何遍历通配符搜索功能

时间:2017-05-23 19:47:52

标签: vba loops

我创建了一个脚本,该脚本将使用通配符搜索给定目录并输出它匹配的任何文件夹。我遇到的问题:有多个文件夹与它匹配的通配符...我的脚本只返回它匹配的第一个文件夹并停止。

我是否可以通过目录(在我的情况下为D:\ P)中输入代码并输出所有匹配的文件夹?

非常感谢任何帮助。谢谢!

这是我的代码:

Dim sFile As String, sPathSeek As String, sPathMatch As String

   Dim sMainPath As String
   sMainPath = sfolderPath 'D:\P\

   Dim Path1 As String 'THIS IS THE FIRST STRING I NEED A WILDCARD TO FIND
   Path1 = "_Links"
   Dim Path2 As String 'THIS IS THE SECOND STRING I NEED A WILDCARD TO FIND
   Path2 = "TLP"


'FIND THE FOLDER THAT CONTAINS THE FIRST PATH USING A WILDCARD
    On Error Resume Next
    sPathSeek = sMainPath & "*" & Path1
    sFile = Dir(sPathSeek, vbDirectory)


    Do While Len(sFile) > 0
        If Left(sFile, 1) <> "." Then
            If (GetAttr(sFile) And vbDirectory) = vbDirectory Then
                sPathMatch = sFile
                Exit Do
            End If
        End If
        sFile = Dir
    Loop


    MsgBox IIf(sPathMatch = "", "Match not found", "Match: " & sPathMatch)

1 个答案:

答案 0 :(得分:0)

Dim Sep as string
'....
Sep = ""
Do While Len(sFile) > 0
    If Left(sFile, 1) <> "." Then
        If (GetAttr(sFile) And vbDirectory) = vbDirectory Then
            sPathMatch = sPathMatch & Sep & sFile
            Sep = ", "
        End If
    End If
    sFile = Dir
Loop


MsgBox IIf(sPathMatch = "", "Match not found", "Match: " & sPathMatch)

编辑:这是一个如何收集直接位于“_Links”下的所有“TLP”文件夹的例子

Sub TestFolderMatches()

    Dim col As Collection, f

    Set col = GetFolderMatches("C:\_Stuff\test")
    For Each f In col
        Debug.Print f
    Next f

End Sub



'Return a collection of folders matching "*\_Links\TLP" given a starting folder
Function GetFolderMatches(startFolder As String) As Collection

    Dim fso, fldr, f, subFldr
    Dim colFolders 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 subFldr In fldr.subFolders
            'collect any folder named "TLP" inside a "_Links" folder
            If subFldr.Name = "TLP" And fldr.Name = "_Links" Then
                colFolders.Add subFldr.Path '<< collect this one
            Else
                colSub.Add subFldr.Path '<< search this one
            End If

        Next subFldr
    Loop

    Set GetFolderMatches = colFolders '<< return the collected folders

End Function