0
votes

What I am trying to do: Export a range of cells from an Excel worksheet as an image in an existing Word document, and then saving this Word document as both a Word document and a PDF file. The name both the Word file and the PDF file should get, is in a cell in the Excel worksheet.

The problem: Almost everything works, except for the .pdf-file. It is generated, but when trying to open it I get an error, saying the file is unreadable.

Can someone help with this? The code I use is below - I assembled it from different examples on this and other forums (I really am a VBA beginner)...

Thank you so much!

The Code:

Sub SaveAsWord()

Dim WordApp As Object
Set WordApp = CreateObject("Word.Application")

Dim WordDoc As Object
Set WordDoc = WordApp.Documents.Open("C:\Users\Jurgen\Documents\remake.docx")

Range("C4:E19").Select
Selection.CopyPicture Appearance:=xlScreen, Format:=xlPicture
WordApp.Visible = True
WordApp.ActiveDocument.Bookmarks("here").Select
Set objSelection = WordApp.Selection
objSelection.Paste

Dim myfilename As String
myfilename = Sheets("Blad1").Range("G15")
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".pdf", _
FileFormat:=wdFormatPDF
WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".docx", _
FileFormat:=wdFormatXMLDocument

End Sub
1

1 Answers

0
votes

As you do not use Early Binding and it also seems that you do not use Option Explicit the root cause will be that wdFormatPDF is 0 and it should be 17.

Either you use Option Explicit and Early Binding or you just replace the constants with the values like that

WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".pdf", _ FileFormat:=17

and

WordApp.ActiveDocument.SaveAs2 Filename:="C:\Users\Jurgen\Documents\" & myfilename & ".docx", _ FileFormat:=12

Reading material

Option Explict

Early vs Late Binding

Late Binding

Microsoft on Using early binding and late binding in Automation