Since Word 2010, the Document object from the Word library includes the method ExportAsFixedFormat(), which allows exporting a Word document to either a PDF file or an XPS file.
Example:
Sub ExportWordToPDF()
Dim appWord As Word.Application
Dim document As Word.Document
Dim folderPath As String
Dim pdfFileName As String
Set appWord = CreateObject("Word.Application")
folderPath = ThisWorkbook.Path & "\Export"
' Open the Word document located in the "Export" subfolder
Set document = appWord.Documents.Add(folderPath & "\DokumentTest01.docx")
' Define the name of the PDF file to be created
pdfFileName = folderPath & "\DokumentTest01.pdf"
' Export the document as PDF
document.ExportAsFixedFormat _
OutputFileName:=pdfFileName, _
ExportFormat:=wdExportFormatPDF
' Close the Word document without saving changes
document.Close SaveChanges:=wdDoNotSaveChanges
' Quit Word application and clean up
appWord.Quit
Set document = Nothing
Set appWord = Nothing
End Sub
Explanation:
- The code exports a Word document located in the Export folder, which is a subdirectory of the folder containing the Excel workbook running this VBA code.
- The OutputFileName parameter specifies the full path and name of the file to be created, which in this example is the same as the Word document’s name but with a .pdf extension.
- The ExportFormat parameter determines the export type. It can be set to:
- wdExportFormatPDF for exporting as a PDF file
- wdExportFormatXPS for exporting as an XPS file (XML Paper Specification format)
- When closing the Word document using the Close() method, the SaveChanges parameter is set to wdDoNotSaveChanges to prevent any modifications to the original Word file.