2020年6月12日
有时候需要将许多word转为pdf,网上搜索了一圈,现成的软件居然要收费。
后来搜到可以用vba解决。遂记录下来
一、系统环境
- windows 10 64bit
- Office 2019或者是wps 2019专业版
wps要专业版,个人版不行。专业版才带vba
二、方法
(1)打开一个空白的word文档或者wps文档。
(2)按下Alt+F11快捷键,打开vba编辑器
(3)在打开的Project中的空白文档处输入如下代码:
Sub ConvertWordsToPdfs()
'Updated by Extendoffice 20181123
Dim xIndex As String
Dim xDlg As FileDialog
Dim xFolder As Variant
Dim xNewName As String
Dim xFileName As String
Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
If xDlg.Show <> -1 Then Exit Sub
xFolder = xDlg.SelectedItems(1) + "\"
xFileName = Dir(xFolder & "*.*", vbNormal)
While xFileName <> ""
If ((Right(xFileName, 4)) <> ".doc" Or Right(xFileName, 4) <> ".docx") Then
xIndex = InStr(xFileName, ".") + 1
xNewName = Replace(xFileName, Mid(xFileName, xIndex), "pdf")
Documents.Open FileName:=xFolder & xFileName, _
ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
wdOpenFormatAuto, XMLTransform:=""
ActiveDocument.ExportAsFixedFormat OutputFileName:=xFolder & xNewName, _
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.Close
End If
xFileName = Dir()
Wend
End Sub
如下图所示:
(4)点击【运行】菜单中的【运行子过程/用户窗体】(或者按下F5),就会打开一个对话框,选择包含多个word文档的文件夹,就可以执行转换操作了。
(5)执行完毕之后,会在word文件所在的目录生成pdf文件。