word批量转PDF文件,只需要修改路径即可!
vbnet
Option Explicit
Sub wordtoPDF()
Dim folderPath As String
Dim outputFolder As String
Dim fileName As String
Dim doc As Document
Dim 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) = "" Then
MkDir outputFolder
End If
' 遍历文件夹中的 Word 文件
fileName = Dir(folderPath & "*.docx")
'Debug.Print fileName
While fileName <> ""
' 打开当前 Word 文档
Set doc = Documents.Open(folderPath & fileName)
' 生成对应的 PDF 文件路径
Dim pdfFileName As String
pdfFileName = outputFolder & Replace(fileName, ".docx", ".pdf")
' 将文档另存为 PDF 格式
doc.SaveAs2 pdfFileName, FileFormat:=wdFormatPDF
' If fileSaved Then
' doc.Saved = True
' End If
' 关闭文档,释放内存
'doc.Close
'doc.Close savechanges:=wdDoNotSaveChanges
doc.Close savechanges:=wdSaveChanges
' 获取下一个 Word 文件
fileName = Dir()
Wend
' 恢复屏幕刷新
Application.ScreenUpdating = True
' 提示转换完成
MsgBox "批量转换完成!请检查 PDF 文件夹。"
End Sub
只转当前活动的word文档为PDF,不是批量化操作
vbnet
Option Explicit
Sub SaveActiveDocumentToPDF()
Dim pdfPath As String
' 生成PDF文件路径:与原文档同路径,仅修改扩展名
pdfPath = Replace(ActiveDocument.FullName, ".docx", ".pdf")
' 如果是.doc格式的文档,可使用下面这行代码
' pdfPath = Replace(ActiveDocument.FullName, ".doc", ".pdf")
' 导出为PDF
ActiveDocument.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相关的高级选项支持可能有限 |