使用Excel VBA将Word文档另存为PDF

时间:2017-03-20 16:36:48

标签: excel word-vba

这与将单词转换为PDF格式有关。

当我在excel VBA中使用以下内容时,我收到错误,不确定此代码是否有问题。

以下是我得到的错误

Run-time error "5": Invalid procedure call or argument

保存到word文档可以正常使用以下代码

objWord.ActiveDocument.SaveAs PathName & NewFileName & ".docx"

此外,下面的工作正常,但问题是它会创建一个非常大的PDF文档。

objWord.ActiveDocument.SaveAs2 Filename:=PathName & NewFileName & ".pdf", _ ' FileFormat:=wdFormatPDF

我在单词中录制了一个宏,将文件保存为PDF,并按照以下修改生成的代码。

objWord.ActiveDocument.ExportAsFixedFormat OutputFileName:= _ PathName & NewFileName & ".pdf", _ ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _ wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _ Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _ CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _ BitmapMissingFonts:=True, UseISO19005_1:=False

请帮我解决此问题。

PS:我使用Excel VBA使用Word文档进行Mailmerge,它工作正常,能够以word格式保存单个文档,但我需要将其保存为PDF格式。感谢。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,它会将其保存在与单词文档声明相同的文件夹中,但它可以正常工作。

    Private Sub Knop2_Click()
 Dim directory As String
 Dim enddirectory As String

    directory = "C:\docs" ' The starting directory
    enddirectory = "C:\pdf" 'einde

    Dim fso, newFile, folder, files
    Set fso = CreateObject("Scripting.FileSystemObject")

    Set folder = fso.GetFolder(directory)
    Set files = folder.files

    For Each file In files


        Dim newName As String
        newName = Replace(file.Path, ".doc", ".pdf")
        newName = Replace(file.Path, ".docx", ".pdf")

        Documents.Open FileName:=file.Path, _
            ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
            PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
            WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
            wdOpenFormatAuto, XMLTransform:=""

        ActiveDocument.ExportAsFixedFormat OutputFileName:=newName, _
            ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
            wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
            Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
            CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
            BitmapMissingFonts:=True, UseISO19005_1:=False

        ActiveDocument.Close


    Next

End Sub