首页 > 解决方案 > 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。

标签: vba

解决方案


通配符用于返回目录中的所有文件或文件夹名称。使用带参数的 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

推荐阅读