2017-09-01 126 views
-2

我給出了一個4位數的橋接計劃編號。我需要找到一個與該橋相對應的文件夾。文件夾名稱將包含橋牌編號和其他一些隨機文本(例如「1234-華盛頓街道」)。我寫了一些能夠實現這一點的代碼,但它非常慢。我想知道是否有人可以用更有效的方式來做到這一點。謝謝。搜索文件夾內的文件夾(Excel-VBA)

Public FSO As New FileSystemObject 

Public Function FoundPlan(bridge_plan As String) 

    Dim objFolder As Folder 
    Dim planFolder As Folder 
    Dim Path As String 
    Dim i As String 


    Path = "G:\some\path" 
    'This is the directory path that carries my list of folders 

    Set objFolder = FSO.GetFolder(Path) 

    If Not Len(bridge_plan) = 4 Then 
     FoundPlan = "" 
     Exit Function 
    End If 
    'If the given plan number is anything except 4 digits, the function returns 
    'nothing and exits 

    For Each planFolder In objFolder.SubFolders 

     If Not InStr(planFolder, bridge_plan) = 0 Then 
      FoundPlan = Path & planFolder 
      Exit For 
     End If 

    Next planFolder 

    'For each subfolder in my directory I use instr to search for my number 
    'inside the folder path. 

End Function 

回答

2

試試這個。它不需要遍歷每個文件夾

Public Function FoundPlan(bridge_plan As String) As String 
    Dim planFolder As String, Path As String 

    Path = "G:\some\path\" 
    'This is the directory path that carries my list of folders 

    If Not Len(bridge_plan) = 4 Then Exit Function 

    planFolder = Dir(Path & bridge_plan & "*", vbDirectory) 

    If Not planFolder = vbNullString Then FoundPlan = Path & planFolder 
End Function 
+0

您能否更詳細地解釋一下「Dir」操作符在做什麼。現在,即使存在文件夾,此功能也不會返回任何內容。 –

+0

你的路是什麼?你是否也包含了最終的'\'? 'Dir'是一個列出文件和文件夾的功能。通過使用'*',它提供了名稱的模糊匹配。 [參考](https://www.techonthenet.com/excel/formulas/dir.php) – Tom

+0

我沒有在'Dir'行中包含反斜槓,所以你的Path需要等於'Path =「G :\ TSB \ Bridge Shared \ Bridge Plans \ Bridge Plans-SCANNED \「' – Tom