2017-05-23 102 views
0

我創建了一個腳本,它將使用通配符搜索給定目錄並輸出它匹配的任何文件夾。我遇到的問題是:有多個文件夾與通配符匹配......我的腳本只返回它匹配並停止的第一個文件夾。如何通過通配符搜索功能進行循環

是否有我可以通過目錄代碼循環(在我的情況下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) 

回答

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」

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 
+0

這不如何收集駐留所有的 「TLP」 文件夾一個例子似乎在代碼中有所作爲,但我仍然獲得相同的輸出,因爲它不會遍歷整個文件夾集。有沒有辦法讓代碼讀取D:\ P \中的所有文件夾,並使用通配符返回任何匹配的文件夾? –

+0

你是在談論正在掃描的路徑的直接子文件夾,或嵌套子文件夾更深層次? –

+0

我試圖讓D:\ P \中的所有文件夾包含一個字符串(本例中通配符是「_Links」或「TLP」)。我在多臺計算機上使用此代碼,並想知道這些計算機上存在哪些「_Links」或「TLP」文件夾。我的代碼只搜索一個文件夾然後停止,我需要它繼續搜索整個D:\ P \並返回其他包含通配符的文件夾。對困惑感到抱歉。 –