使用SaveAsFile时,Outlook损坏PDF

时间:2019-02-01 17:38:47

标签: vba pdf outlook-vba

我用下面的代码在Outlook中自动导出PDF文件时,他们在我的收件箱到达。但是,它保存的文件已损坏。 SaveAsFile方法仅采用一个参数-保存到的文件路径-在文档中没有说我可以传递文件类型。如何保存这些PDF附件而不损坏文件?

    Private WithEvents Items As Outlook.Items

    Private Sub Application_Startup()

        'Declaring Variables [BD]
        Dim oOutlook As Outlook.Application
        Dim oNameSpace As Outlook.NameSpace
        Dim oFolder As Outlook.MAPIFolder

        'Intializing Variables [BD]
        Set oOutlook = Outlook.Application
        Set oNameSpace = Application.GetNamespace("MAPI")

        Set oFolder = oNameSpace.GetDefaultFolder(olFolderInbox).Parent
        Set oFolder = oFolder.Folders("Produce Availability").Folders("Earls Organic")
        Set Items = oFolder.Items

    End Sub

    Private Sub Items_ItemAdd(ByVal Item As Object)

    'Declaring Variables [BD]
    Dim sOutputFileName As String

    Dim oMessage As Outlook.MailItem
    Dim oAttachment As Outlook.Attachments

    'Initializing Variables [BD]
    sDateTime = Format(Now(), "yyyymmddhhnnss")
    sOutputFolderPath = "C:\Earls Organic\"

        On Error GoTo ErrorHandler

        If TypeName(Item) = "MailItem" Then

            Set oMessage = Item
            Set oAttachment = oMessage.Attachments

            sOutputFileName = oMessage.Subject & " " & sDateTime
            sOutputFolderPathAndName = sOutputFolderPath & sOutputFileName & ".pdf"
            oAttachment.Item(1).SaveAsFile sOutputFolderPathAndName

            Set oAttachment = Nothing
            Set oItem = Nothing

        End If

    ProgramExit:
        Exit Sub

    ErrorHandler:
            MsgBox Err.Number & " - " & Err.Description
            Resume ProgramExit

    End Sub

2 个答案:

答案 0 :(得分:1)

根据要求,以下是我的评论作为答案:

您确定附件(1)是PDF文件吗?签名和图像可以记录为附件。您应该向下扫描附件集合,检查扩展名,直到找到PDF文件。

答案 1 :(得分:0)

SaveAsFile不会损坏文件。您从不检查文件是否实际上是PDF-您可以具有其他附件,这些附件在Outlook中可能会或可能不会被视为(例如图像)。您假定第一个附件是PDF。遍历所有附件时,请检查Attachment.FileName属性,以确保获得期望的结果。