【问题标题】:save PDF attachment with filename &domain name保存带有文件名和域名的 PDF 附件
【发布时间】:2020-05-26 14:24:33
【问题描述】:

我想运行一个宏来执行以下步骤: - 仅将 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

【问题讨论】:

    标签: vba outlook


    【解决方案1】:

    以下代码行检索资源管理器窗口中的活动文件夹,而不是收件箱。 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 方法来仅获取与您的条件相对应的项目。在以下文章中详细了解这些方法:

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

    olAttachment.SaveAsFile strFolderPath & domainName & strFileName
    

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

    【讨论】:

      猜你喜欢
      • 2014-11-26
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2015-01-10
      相关资源
      最近更新 更多