Home:ALL Converter>Export docx to pdf with vba

Export docx to pdf with vba

Ask Time:2022-02-06T23:21:56         Author:Elo

Json Formatter

I would like to export docx file to pdf file from excel vba. Document file.docx is opened correctly. However, an error occurred while calling the method ExportAsFixedFormat: Run-time error '5': Invalid procedure call or argument. I think arguments are ok.

Next little bug: ActiveDocument.Path does not work. There is an error "Run-time error '424': Object required" Therefore I used WordApp.Documents(myFileName).ExportAsFixedFormat instead ActiveDocument.ExportAsFixedFormat.

This code is executed from file Macro.xlsm. I use Microsoft Office 2021.

Method exportasfixedformat

Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp

Set WordApp = CreateObject("Word.Application")
FileNameDoc = "D:\rd\file.docx"

WordApp.Documents.Open FileNameDoc
WordApp.Visible = True
WordApp.Documents(FileNameDoc).Activate ' <- activation doesn't work

fileNamePdf = "D:\rd\file.pdf"
'fileNamePdf = ActiveDocument.Path & "\" & "file.pdf" 

' https://learn.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
' here is error: Run-time error '5': Invalid procedure call or argument
WordApp.Documents(myFileName).ExportAsFixedFormat OutputFileName:=fileNamePdf, _
                                                             ExportFormat:=wdExportFormatPDF, _
                                                             OpenAfterExport:=False, _
                                                             OptimizeFor:=wdExportOptimizeForPrint, _
                                                             Range:=wdExportAllDocument, _
                                                             Item:=wdExportDocumentWithMarkup, _
                                                             IncludeDocProps:=False, _
                                                             CreateBookmarks:=wdExportCreateNoBookmarks, _
                                                             BitmapMissingFonts:=True

' https://learn.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordApp.Documents(myFileName).Close _
'ActiveDocument.Close _ 
    SaveChanges:=wdSaveChanges, _ 
    OriginalFormat:=wdOriginalDocumentFormat

Any idea for a solution?

Author:Elo,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/71008618/export-docx-to-pdf-with-vba
yy