有沒有辦法存盤使用通配符時找到的目錄?例如,如果我有檢查目錄是否存在的代碼:
Public Function DirectoryFinder(PartialFolderName As String)
Dim FilePath As String
If Dir(CurrentProject.Path & "\DataFolder\" & PartialFolderName & "*", vbDirectory)<>"" Then
'FilePath = ???
End If
End Function
當前專案位于 C:\Folder 中,所需的完整檔案路徑為 C:\Folder\DataFolder\PartialFolderName12345。
有沒有辦法在 FilePath 變數中捕獲 Dir() 函式找到的目錄?如果我將 FilePath 定義如下,我不相信它會捕獲找到的目錄:
FilePath=CurrentProject.Path & "\DataFolder\" & PartialFolderName & "*"
相反,它將 FilePath 設定為等于字串“C:\Folder\DataFolder\PartialFolderName*”,這對我所需要的不起作用。
我希望能夠捕獲的是完整的“C:\Folder\DataFolder\PartialFolderName12345”
uj5u.com熱心網友回復:
將 Dir 函式的結果直接賦值給變數并檢查它是否為空:
Dim FilePath As String, BasePath as String
BasePath = CurrentProject.Path & "\DataFolder\"
FilePath = Dir(BasePath & PartialFolderName & "*", vbDirectory)
If FilePath <>"" Then
' FilePath now contains the name of the folder that was found.
' The full Path would be BasePath & FilePath
...
End If
uj5u.com熱心網友回復:
像這樣的東西?
Sub Test()
Dim MyPath As String
MyPath = DirectoryFinder("SomeFolder123")
End Sub
Public Function DirectoryFinder(PartialFolderName As String) As String
Dim FilePath As String
FilePath = Dir(CurrentProject.Path & "\DataFolder\" & PartialFolderName & "*", vbDirectory)
If FilePath <> "" Then
DirectoryFinder = CurrentProject.Path & "\DataFolder\" & FilePath
End If
End Function
uj5u.com熱心網友回復:
值得注意的是,vbDirectory它將找到與提供的模式匹配的檔案夾和檔案,因此您應該考慮確保您找到的是檔案夾而不是檔案。也可能允許 >1 個檔案夾與您的模式匹配的情況。
Sub tester()
Dim folders As Collection
Set folders = MatchedDirectories("C:\Tester\", "tmp -*")
Debug.Print folders.Count
If folders.Count = 0 Then
'no matches
ElseIf folders.Count = 1 Then
'one match
Else
'multiple matches
End If
End Sub
Public Function MatchedDirectories(searchIn As String, PartialFolderName As String) As Collection
Dim f As String, col As New Collection
If Right(searchIn, 1) <> "\" Then searchIn = searchIn & "\"
f = Dir(searchIn & PartialFolderName, vbDirectory)
Do While Len(f) > 0
'make sure it's a directory we found...
If GetAttr(searchIn & f) = vbDirectory Then col.Add searchIn & f
f = Dir()
Loop
Set MatchedDirectories = col
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/325984.html
上一篇:自定義函式,如msgbox函式
下一篇:無法識別VBA格式編號
