/
WordToPDF.bas
53 lines (39 loc) · 1.89 KB
/
WordToPDF.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Attribute VB_Name = "Module1"
Option Explicit
'This is a PDF to Text conversion macro
Sub WordToPDF()
'Define the variables
Dim InputWordFileName As String
Dim BaseFolderPath As String
Dim WordExtension As String
Dim OutputPDFFile As String
Dim objWordApp As Word.Application
Dim objMyWordFile As Word.document
Set objWordApp = CreateObject("Word.Application")
'Add Error Handler to catch error, if any
On Error GoTo ErrHandler
'Clear the cells where the error description and number will be updated, when encountered
ThisWorkbook.Worksheets("Sheet1").Range("B3").Value = ""
ThisWorkbook.Worksheets("Sheet1").Range("B4").Value = ""
'Retrieve input values: Word filename and Basepath from cell B1 and B2
InputWordFileName = ThisWorkbook.Worksheets("Sheet1").Range("B1").Value
BaseFolderPath = ThisWorkbook.Worksheets("Sheet1").Range("B2").Value
'Determine the file extension - .doc or .docx
WordExtension = Right(InputWordFileName, Len(InputWordFileName) - InStrRev(InputWordFileName, "."))
MsgBox ("Word Ext = " & WordExtension)
'Open the word file
Set objMyWordFile = objWordApp.documents.Open(BaseFolderPath & InputWordFileName)
objWordApp.Visible = True
'Create file name with .pdf extension
OutputPDFFile = BaseFolderPath & Replace(objMyWordFile.Name, WordExtension, "pdf")
'Convert word file to PDF and save it in the basepath
objWordApp.activedocument.ExportAsFixedFormat OutputFileName:=OutputPDFFile, ExportFormat:=wdExportFormatPDF
'Close the Word file and word application
objMyWordFile.Close
objWordApp.documents.Application.Quit
Exit Sub
ErrHandler:
'On error, save the error details
ThisWorkbook.Worksheets("Sheet1").Range("B3").Value = Err.Description
ThisWorkbook.Worksheets("Sheet1").Range("B4").Value = Err.Number
End Sub