Hello,
I was just wondering if there was a VBA/Macro script to run in a workbook that would print or save multiple word documents as pdfs in a specific folder?
Thanks for your time,
Joshua
VBA/Macro Word doc to PDF
-
- Administrator
- Posts: 80088
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: VBA/Macro Word doc to PDF
Try this - it is untested. Replace C:\Word\ with the folder path; keep the \ at the end.
Code: Select all
Sub ExportDocs()
Const strFolder As String = "C:\Word\"
Dim strFile As String
Dim strPDF As String
Dim lngPos As Long
Dim objWrd As Object ' Word.Application
Dim objDoc As Object ' Word.Document
Dim f As Boolean
On Error Resume Next
Set objWrd = GetObject(Class:="Word.Application")
If objWrd Is Nothing Then
Set objWrd = CreateObject(Class:="Word.Application")
f = True
End If
On Error GoTo ErrHandler
strFile = Dir(strFolder & "*.doc*")
Do While strFile <> ""
Set objDoc = objWrd.Documents.Open(Filename:=strFolder & strFile)
lngPos = InStrRev(strFile, ".")
strPDF = Left(strFile, lngPos) & "pdf"
objDoc.ExportAsFixedFormat OutputFileName:=strFolder & strPDF, ExportFormat:=17 ' wdExportFormatPDF
objDoc.Close SaveChanges:=False
strFile = Dir
Loop
ExitHandler:
On Error Resume Next
If f Then
objWrd.Quit SaveChanges:=False
End If
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
Best wishes,
Hans
Hans
-
- 2StarLounger
- Posts: 120
- Joined: 16 Oct 2021, 16:22
Re: VBA/Macro Word doc to PDF
Wow, it works great.
Thank you Hans
Thank you Hans
-
- PlutoniumLounger
- Posts: 16801
- Joined: 24 Jan 2010, 23:23
- Location: brings.slot.perky
Re: VBA/Macro Word doc to PDF
Hi Hans.
Just curious.
Why "On Error"?
Is that to trap a file not existing?
If so why not test with a procedure blnFileExists and report the (false) results of that?
Such a pre-processor could alert the user that one or more files are missing before generating the remaining files.
Cheers, Chris
Fill your face with laughter, then there will be no room for tears.
-
- Administrator
- Posts: 80088
- Joined: 16 Jan 2010, 00:14
- Status: Microsoft MVP
- Location: Wageningen, The Netherlands
Re: VBA/Macro Word doc to PDF
I used a generic error handler for the following section as a whole:
So whether a file cannot be opened, or cannot be saved as PDF. or any other problem occurs, the error handler will catch it.
Code: Select all
strFile = Dir(strFolder & "*.doc*")
Do While strFile <> ""
Set objDoc = objWrd.Documents.Open(Filename:=strFolder & strFile)
lngPos = InStrRev(strFile, ".")
strPDF = Left(strFile, lngPos) & "pdf"
objDoc.ExportAsFixedFormat OutputFileName:=strFolder & strPDF, ExportFormat:=17 ' wdExportFormatPDF
objDoc.Close SaveChanges:=False
strFile = Dir
Loop
Best wishes,
Hans
Hans
-
- PlutoniumLounger
- Posts: 16801
- Joined: 24 Jan 2010, 23:23
- Location: brings.slot.perky
Re: VBA/Macro Word doc to PDF
Thanks, Chris
Fill your face with laughter, then there will be no room for tears.