首页 > 解决方案 > 保存带有文件名和域名的 PDF 附件

问题描述

我想运行一个宏来执行以下步骤: - 仅将 PDF 附件保存到硬盘 - 使用修改名称文件名和域名保存它。这是我从开源中搜索并将其混合在一起的代码。任何帮助表示赞赏。谢谢

Public Sub Download_Attachments()

    Dim ns As NameSpace
    Dim olFolder_Inbox As Folder
    Dim olMail As MailItem
    Dim olAttachment As Attachment
    Dim strFolderPath As String
    Dim strFileName As String
    Dim strSenderAddress As String
    Dim strSenderDomain As String
    Dim fso As Object


    strFolderPath = "C:\"

    Set ns = GetNamespace("MAPI")
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set olFolder_Inbox = Application.ActiveExplorer.CurrentFolder


      Set olMail = Application.ActiveWindow.CurrentItem

'Get sender domain
      strSenderAddress = olMail.SenderEmailAddress
      strSenderDomain = Right(strSenderAddress, Len(strSenderAddress) - InStr(strSenderAddress, "@"))



    For Each olMail In olFolder_Inbox.Items

        If TypeName(olMail) = "MailItem" And olMail.Attachments.Count > 0 Then


           For Each olAttachment In olMail.Attachments

                Select Case UCase(fso.GetExtensionName(olAttachment.FileName))

                    Case "PDF", "pdf"
                        olAttachment.SaveAsFile strFolderPath & strFileName


                    Case Else
                        'skip

                End Select

           Next olAttachment

        End If


    Next olMail

    Set olFolder_Inbox = Nothing
    Set fso = Nothing
    Set ns = Nothing

End Sub

标签: vbaoutlook

解决方案


以下代码行检索资源管理器窗口中的活动文件夹,而不是收件箱。Outlook 可以使用任何活动文件夹启动,您可以为 Outlook.exe 文件指定文件夹名称。要获取默认文件夹(收件箱),您需要使用NameSpace.GetDefaultFolder方法,该方法返回一个Folder对象,该对象代表当前配置文件所请求类型的默认文件夹;例如,获取当前登录用户的默认日历文件夹。例如,以下示例代码使用该CurrentFolder属性将显示的文件夹更改为用户的默认Inbox文件夹。

Sub ChangeCurrentFolder()  
 Dim myNamespace As Outlook.NameSpace  

 Set myNamespace = Application.GetNamespace("MAPI")  
 Set Application.ActiveExplorer.CurrentFolder = myNamespace.GetDefaultFolder(olFolderInbox) 

End Sub

那么真的不建议遍历文件夹中的所有项目。

For Each olMail In olFolder_Inbox.Items

相反,您需要使用 Items 类的Find/FindNextRestrict方法来仅获取与您的条件相对应的项目。在以下文章中阅读有关这些方法的更多信息:

最后,您感兴趣的部分是将附件保存到指定路径的类的SaveAsFile方法:Attachment

olAttachment.SaveAsFile strFolderPath & domainName & strFileName

确保将合格的文件路径作为参数传递。我建议在调试器下运行代码并查看传递了哪些值。


推荐阅读