VBA实现word文档批量转PDF文件
word批量转PDF文件,只需要修改路径即可!
Option ExplicitSub wordtoPDF()Dim folderPath As StringDim outputFolder As StringDim fileName As StringDim doc As DocumentDim fileSaved As Boolean' 关闭屏幕刷新,提升性能Application.ScreenUpdating = False' 设置输入和输出文件夹路径(只需修改这里)
' folderPath = "C:\Users\YourName\Docs\WordFiles\" ' Word 文件所在文件夹
' outputFolder = "C:\Users\YourName\Docs\PDFFiles\" ' PDF 保存文件夹folderPath = "D:\exceldata\VBA_word\word\" ' Word 文件所在文件夹outputFolder = "D:\exceldata\VBA_word\word\" ' PDF 保存文件夹' 检查输出文件夹是否存在,不存在则创建If Dir(outputFolder, vbDirectory) = "" ThenMkDir outputFolderEnd If' 遍历文件夹中的 Word 文件fileName = Dir(folderPath & "*.docx")'Debug.Print fileNameWhile fileName <> ""' 打开当前 Word 文档Set doc = Documents.Open(folderPath & fileName)' 生成对应的 PDF 文件路径Dim pdfFileName As StringpdfFileName = outputFolder & Replace(fileName, ".docx", ".pdf")' 将文档另存为 PDF 格式doc.SaveAs2 pdfFileName, FileFormat:=wdFormatPDF' If fileSaved Then
' doc.Saved = True
' End If' 关闭文档,释放内存'doc.Close'doc.Close savechanges:=wdDoNotSaveChangesdoc.Close savechanges:=wdSaveChanges' 获取下一个 Word 文件fileName = Dir()Wend' 恢复屏幕刷新Application.ScreenUpdating = True' 提示转换完成MsgBox "批量转换完成!请检查 PDF 文件夹。"
End Sub
只转当前活动的word文档为PDF,不是批量化操作
Option ExplicitSub SaveActiveDocumentToPDF()Dim pdfPath As String' 生成PDF文件路径:与原文档同路径,仅修改扩展名pdfPath = Replace(ActiveDocument.FullName, ".docx", ".pdf")' 如果是.doc格式的文档,可使用下面这行代码' pdfPath = Replace(ActiveDocument.FullName, ".doc", ".pdf")' 导出为PDFActiveDocument.ExportAsFixedFormat _OutputFileName:=pdfPath, _ExportFormat:=wdExportFormatPDF, _OpenAfterExport:=True ' 设置为True可在导出后自动打开PDF'获取原文档路径: ActiveDocument.FullName 用于获取当前文档的完整路径和文件名?''构造PDF路径:使用 Replace 函数将原文件扩展名(如".docx")替换为".pdf"。''导出PDF:ExportAsFixedFormat 是核心方法,参数 wdExportFormatPDF 表示导出格式为PDF'''导出后操作:将 OpenAfterExport 设置为 True,导出后会自动打开PDF文件。End Sub
wdExportFormatPD和wdFormatPDF的区别
| 特性维度 | wdExportFormatPDF | wdFormatPDF |
|---|---|---|
| 主要用途 | 通过ExportAsFixedFormat方法导出为PDF | 通过SaveAs或SaveAs2方法另存为PDF |
| 所属方法 | ExportAsFixedFormat | SaveAs2 |
| 功能特点 | 提供更精细的PDF输出控制,如导出范围、图像质量优化、书签处理等 | 主要用于指定文件格式,PDF相关的高级选项支持可能有限 |
