Saving Word document as PDF

天涯浪子 提交于 2021-02-08 10:35:56

问题


This is related to converting a Word document to PDF format.

I get an error in my Excel VBA code.

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

Saving into a Word document works

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

The below runs but it creates a PDF document which is very big in size.

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

I recorded a macro in Word to save the file as PDF and modified the generated code as per below.

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

I am using Excel VBA to do a Mailmerge using Word document and it is working fine and able to save individual documents in Word format but I need to save it in PDF format.


回答1:


Try this code, it does save it in the same folder as where the word documents are stated but it works.

    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


来源:https://stackoverflow.com/questions/42909112/saving-word-document-as-pdf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!