捕获使用通配符找到的目录值

  • 本文关键字:通配符 vba ms-access
  • 更新时间 :
  • 英文 :


是否有办法存储使用通配符时找到的目录?例如,如果我有检查目录是否存在的代码:

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:FolderDataFolderPartialFolderName12345。

是否有一种方法可以捕获由FilePath变量中的Dir()函数找到的目录?如果我将FilePath定义为如下所示,我认为它无法捕获找到的目录:

FilePath=CurrentProject.Path & "DataFolder" & PartialFolderName & "*"

相反,它将FilePath设置为字符串"C:FolderDataFolderPartialFolderName*",这对我所需要的不起作用。

我想要能够捕获的是完整的"C:FolderDataFolderPartialFolderName12345">

像这样?

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

将Dir-function的结果直接赋值给变量,并检查其是否为空:

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

值得注意的是,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

相关内容

  • 没有找到相关文章

最新更新