【问题标题】:Outlook Saving Attachment with Subject Name带有主题名称的 Outlook 保存附件
【发布时间】:2017-12-18 08:14:17
【问题描述】:

我有一个宏,可以将收件箱中电子邮件的所有附件保存到指定目录。但是,我想以电子邮件主题作为文件名保存附件。

这是我的第一个宏,也是第一次查看 VBA,因此非常感谢任何指针。

Private Sub Outlook_VBA_Save_Attachment()
    ''Variable declarions
    Dim ns As NameSpace
    Dim inb As Folder
    Dim itm As MailItem
    Dim atch As Attachment

    ''Variables Initialization
    Set ns = Outlook.GetNamespace("MAPI")
    Set inb = ns.GetDefaultFolder(olFolderInbox)
    File_Path = "H:\Notes\"

    ''Loop Thru Each Mail Item
    For Each itm In inb.Items

    ''Loop Thru Each Attachment
        For Each atch In itm.Attachments
            If atch.Type = olByValue Then
               atch.SaveAsFile File_Path & atch.FileName
            End If
        Next atch
    Next itm

    '''''Notify the Termination of Process
    MsgBox "Attachments Extracted to: " & File_Path
End Sub

【问题讨论】:

    标签: vba outlook


    【解决方案1】:

    你需要做的就是改变一行:

    atch.SaveAsFile File_Path & itm.Subject
    

    要包含原始文件扩展名,您可以使用 FileSystemObject 来获取它。修改后的代码如下:

    Private Sub Outlook_VBA_Save_Attachment()
        ''Variable declarions
        Dim ns As Namespace
        Dim inb As Folder
        Dim itm As MailItem
        Dim atch As Attachment
        Dim fso As FileSystemObject
    
        ''Variables Initialization
        Set ns = Outlook.GetNamespace("MAPI")
        Set inb = ns.GetDefaultFolder(olFolderInbox)
        File_Path = "H:\Notes\"
        Set fso = New FileSystemObject
    
        ''Loop Thru Each Mail Item
        For Each itm In inb.Items
    
        ''Loop Thru Each Attachment
            For Each atch In itm.Attachments
                If atch.Type = olByValue Then
                   atch.SaveAsFile File_Path & itm.Subject & "." & fso.GetExtensionName(atch.Filename)
                End If
            Next atch
        Next itm
    
        '''''Notify the Termination of Process
        MsgBox "Attachments Extracted to: " & File_Path
    End Sub
    

    这需要参考 Microsoft Scripting Runtime。

    【讨论】:

    • 这确实有效,所以谢谢你,但是它删除了文件扩展名。有没有办法解决这个问题?
    • 我修改了代码示例以包含文件扩展名。
    • 漂亮!谢谢您的帮助。对于未来的用户,这是您启用对 MS Scripting Runtime 的引用的方式。 stackoverflow.com/questions/3233203/…
    • 请记住,如果有多个附件,您只会得到最后一个,因为您总是覆盖附件。更好的解决方案是将主题和附件文件名结合起来:atch.SaveAsFile File_Path & itm.Subject & " - " & atch.FileName,。您还需要确保没有无效(对于文件名)字符,例如“:”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多