如何将日期添加到附件名称?

How do I add date to attachment name?

我的 VBA 代码将附件从电子邮件下载到我的本地驱动器。我想重命名附件以包含日期。日期应为收到电子邮件的前一天。

Public Sub SaveAutoAttach(item As Outlook.MailItem)

Dim object_attachment As Outlook.Attachment

Dim saveFolder As String
' Folder location when I want to save my file
saveFolder = "\gbhxxxx\Groups\Shared\EBS\Post Go-Live\Auto MT940 download Test"

For Each object_attachment In item.Attachments

    ' Criteria to save .940 files only
    If InStr(object_attachment.DisplayName, "UKAutoMT940") Then
        object_attachment.SaveAsFile saveFolder & "\" & object_attachment.DisplayName
    End If

Next

End Sub

更新了下面的代码以在显示文件名之前附加日期。为此,我们使用 DATEADD 并将 -1 天添加到收到的日期,并将日期时间值格式化为带有“-"s instead of "/”s.

的日期值

如果您想在文件名之后但在扩展名之前添加它,我们需要解析为文件名。

Public Sub SaveAutoAttach(item As Outlook.MailItem)

Dim object_attachment As Outlook.Attachment

Dim saveFolder As String
' Folder location when I want to save my file
saveFolder = "\gbhxxxx\Groups\Shared\EBS\Post Go-Live\Auto MT940 download Test"


    For Each object_attachment In item.Attachments
' Criteria to save .940 files only

    If InStr(object_attachment.DisplayName, "UKAutoMT940") Then

       object_attachment.SaveAsFile saveFolder & "\" & Format(DateAdd("d", -1, item.ReceivedTime), "dd-mm-yyyy") & "_" & object_attachment.DisplayName
    End If

    Next

End Sub