The code that you have used is for Word and uses a lot of Word constants e.g. wdExportFormatPDF
, wdExportOptimizeForPrint
, wdExportDocumentWithMarkup
, wdExportCreateNoBookmarks
, wdSaveChanges
, wdOriginalDocumentFormat
. Excel does not understand what these are.
You have two options. The best option is to set a reference to the Word library. In the Visual Basic Editor select References from the Tools menu. In the resulting dialog page down (approx 16 times) until you see the entry for the Microsoft Word Object library and check the box next to it.
Your other option is to create constants in your code for each Word constant you want to use. You’ll need to use the object browser in Word, or the online help, to look up the values.
Similarly, Excel does not understand ActiveDocument
. You need to prefix any Word objects you wish to use with WordApp
. However, it would be better if you used a variable to point to the document you open:
Set WordDoc = WordApp.Documents.Open(FileNameDoc)
You can then use the WordDoc
variable instead of ActiveDocument
Dim fileNameDoc As String
Dim fileNamePdf As String
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = CreateObject("Word.Application")
fileNameDoc = "D:\rd\file.docx"
Set WordDoc = WordApp.Documents.Open(fileNameDoc)
WordApp.Visible = True
fileNamePdf = WordDoc.Path & "\" & "file.pdf"
' https://docs.microsoft.com/en-us/office/vba/api/word.document.exportasfixedformat
WordDoc.ExportAsFixedFormat OutputFileName:=fileNamePdf, _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
Item:=wdExportDocumentWithMarkup, _
IncludeDocProps:=False, _
CreateBookmarks:=wdExportCreateNoBookmarks, _
BitmapMissingFonts:=True
' https://docs.microsoft.com/en-us/office/vba/api/word.document.close(method)'
WordDoc.Close _
SaveChanges:=wdSaveChanges, _
OriginalFormat:=wdOriginalDocumentFormat
CLICK HERE to find out more related problems solutions.