vba - DIR 无法识别通配符“*”
问题描述
以下代码未找到该文件:xTempTmtl = "Z:\20.0 Global storage\20.1 Design Packages*" & xNewName
其中 xNewName = "SLR-D&C-MI0-000-TRS-007199.Pdf"
但
xTempFol = Dir("Z:\20.0 Global storage\20.1 Design Packages\DP01.1 Stops - Zone C (North)\02. Transmittals\" & xNewName) 找到文件。
问题是文件 xNewName 可能位于 80 个文件夹(Dp01.1...、DP01.2...)等中的任何一个文件夹中,然后在 \02 中。传输\
如果我在 * 后面加上 \,我会收到 Bad file name 错误。
为什么无法识别通配符“*”?
这发生在两台不同的机器上,一台在 Windows 和 PC 上运行 EXCEL2010,另一台在 Windows10 笔记本电脑上运行 EXCEL365。
解决方案
通配符用于返回目录中的所有文件或文件夹名称。使用带参数的 Dir() 函数会更改函数搜索文件的路径。对 Dir() 函数的后续调用将在上一次调用之后返回下一个文件或文件夹。Dir() 不会在子目录中搜索文件。
您需要将 Dir() Attributes 参数递归设置为 vbDirectory 以返回子文件夹名称,然后搜索每个子文件夹。
您可以找到大量使用 FileSystemObject 递归搜索子文件夹以查找文件的示例。我认为编写一个使用 Dir() 函数的函数会很有趣。
Function FindFile(ByVal folderName As String, ByVal FileName As String, Optional ByRef FoundFile As String) As String
Dim search As String
Dim dirList As New Collection
If Not Right(folderName, 1) = "\" Then folderName = folderName & "\"
search = Dir(folderName & "\*", vbDirectory)
While Len(search) > 0
If Not search = "." And Not search = ".." Then
If GetAttr(folderName & search) = 16 Then
dirList.Add folderName & search
Else
If LCase(search) = LCase(FileName) Then
FoundFile = folderName & FileName
FindFile = FoundFile
Exit Function
End If
End If
End If
search = Dir()
Wend
Dim fld
For Each fld In dirList
If Len(FoundFile) > 0 Then
FindFile = FoundFile
Exit Function
Else
FindFile = FindFile(CStr(fld), FileName, FoundFile)
End If
Next
End Function
推荐阅读
- node.js - 在 node express 应用中设置唯一的用户昵称
- parsing - 编译器是否足够聪明,可以根据值在需要该类型的函数中的用法来推断解析值的类型?
- sql - 点燃 - java-jdbc 集成
- android - 如何使用不同的参数多次重复相同的 API 请求并进行第二次网络调用以使用 RxJava 将这些数据发送回服务器
- php - MYSQL 类似数组的 SELECT 语句
- asp.net-mvc - 带有 Microsoft OCR 的 asp.net MVC
- ios - 如何在 swift 4 中设置对 collectionView 的关注?
- angular - Angular ngIf 动画失败
- node.js - npm WARN 没有存储库字段,没有许可证字段
- python - 如何在pytest中进行依赖参数化?