如何使用模式查找文件?

How to find a file using a pattern?

我有一个脚本可以从文件夹中抓取文件并将其附加到电子邮件中。

代码运行但没有任何反应。我认为这是因为 strLocation 是空的。

这是我试图抓取的文件路径的示例:

"C:\Users\MChambers\Desktop\Pricing Reports\Pricing_Report_201908121239 Formatted.xlsx"

Option Explicit

Const olMailItem = 0

Function FindFirstFile(strDirPath, strPattern)
    Dim strResult

    Dim objRegExp, objMatches
    Set objRegExp = New RegExp
    objRegExp.Pattern = strPattern
    objRegExp.IgnoreCase = True

    Dim objFso, objFolder, objFile
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(strDirPath)

    For Each objFile in objFolder.Files
        Set objMatches = objRegExp.Execute(objFile.Name)
        If objMatches.Count > 0 Then
            strResult = objMatches(0).Value
            Exit For
        End If
    Next

    If Len(strResult) > 0 Then
        If Right(strDirPath, 1) <> "\" Then strDirPath = strDirPath & "\"
        strResult = strDirPath & strResult
    End If

    FindFirstFile = strResult
End Function

Sub SendBasicEmail()
    Dim olApp: Set olApp = CreateObject("Outlook.Application")
    Dim olEmail: Set olEmail = olApp.CreateItem(olMailItem)
    Dim strLocation
    Dim strPattern
    strPattern = "Pricing_Report_*Formatted.xlsx"
    strLocation = FindFirstFile("C:\Users\MChambers\Desktop\Pricing Reports\", strPattern)

    If strLocation <> "" Then
        With olEmail 
            .SentOnBehalfOfName = "genericemail"
            .Attachments.Add (strLocation)
            .To = "myemail"
            .Subject = "Subject"
            .Send
        End With
    End If
End Sub

SendBasicEmail

更新:下面的解决方案是正确的。此外,我不得不在我在上面的代码中更新的文件末尾直接调用 sub。

您使用的模式并不像您认为的那样。

strPattern = "Pricing_Report_*Formatted.xlsx"

您似乎希望上面的内容进行通配符匹配(即 "Pricing_Report_" 后跟任意数量的文本和 "Formatted.xlsx")。这不是正则表达式的工作方式。 * 在正则表达式中表示 "zero or more times the preceding expression"。字符.在正则表达式中也有特殊含义,即"any character except line-feed. Because of that your pattern would actually match the string "Pricing_Report"后跟任意数量的连续下划线,字符串"Formatted",除行外的任意单个字符-feed,以及字符串 "xlsx".

将模式更改为此

strPattern = "Pricing_Report_.*Formatted\.xlsx"

并且代码将执行您想要的操作。

有关 VBScript 中正则表达式的更多信息 see here