如圖,在vba編輯窗口,選擇“工具--》引用”
sub batchConvert2pdf()
'需要轉換的word文檔的個數
dim total as Integer
'定義文件名數組:數組的個數根據需要進行設置
Dim fns(total) As String
fns(0) = "d:\doc\1.docx"
'.....................
fns(total-1) = "d:\doc\n.docx"
'定義PDF文件名和Word文件名
Dim pdf, doc As String
'定義文件對象,用於file操作
Dim fso As New Scripting.FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
Dim i As Integer
For i = 0 To total-1
doc = fns(i)
pdf = changeExtension(doc,"pdf")
'如果pdf已經存在,進行下一個
If fso.FileExists(pdf) Then GoTo endflag
If fso.FileExists(doc) Then GoTo endflag
'打開Word
Documents.Open doc
On Error GoTo mflag
ActiveDocument.Convert
ActiveDocument.Save
mflag:
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
pdf _
, ExportFormat:=wdExportFormatPDF, OpenAfterExport:=false, OptimizeFor:= _
wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
ActiveDocument.Save
ActiveDocument.Close
endflag: Next i
end sub
'改變擴展名
Function changeExtension(filename, ext)
Dim extension As String
extension = IIf((Mid(ext, 1, 1) = "."), Mid(ext, 2), ext)
Dim loc As Integer
loc = InStrRev(filename, "\")
Dim dotloc As Integer
dotloc = InStr(loc, filename, ".")
Dim flen As Integer
flen = Len(filename)
If loc = flen Then
changeExtension = ""
Exit Function
End If
If dotloc < loc Then
changeExtension = filename + "." + extension
Exit Function
End If
changeExtension = Mid(filename, 1, dotloc) + extension
End Function