2017-09-01 139 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