跳到主要内容

如何将多个Word文档批量转换为pdf文件?

使用Word中的“另存为”功能,很容易将Word文档转换为PDF文件。 但是,如果您想一次将文件夹中的所有Word文档转换为单独的PDF文件,那么如何实现呢? 本文将向您展示VBA代码,以将多个Word文档批量转换为Word中的pdf文件。

使用VBA将多个Word文档批量转换为pdf文件
使用 Kutools for Word 将多个 Word 文档批量转换为 pdf 文件


使用VBA将多个Word文档批量转换为pdf文件

以下VBA代码可帮助您快速将文件夹中的所有Word文档立即转换为pdf文件。 请执行以下操作。

1.在Word中,按 其他 + F11 键打开 Microsoft Visual Basic应用程序 窗口。

2.在 Microsoft Visual Basic应用程序 窗口中,单击 插页 > 模块,然后将以下VBA代码复制到“模块”窗口中。

VBA代码:在Word中将多个Word文档批量转换为pdf文件

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

3。 按 F5 键来运行代码。

4.弹出浏览对话框,请选择包含要转换为pdf文件的Word文档的文件夹,然后单击 OK 按钮。

然后,所选文件夹中的所有Word文档将立即转换为单独的pdf文件。 看截图:


使用 Kutools for Word 将多个 Word 文档批量转换为 pdf 文件

如果很难处理VBA代码,则可以尝试 转换文件 实用程序 Kutools for Word 来解决这个问题。

Kutools for Word :拥有100多个方便的Word加载项, 免费试用,没有限制 60.

1。 点击 Kutools 加 > 文件/文件。 看截图:

2.在 文件格式转换器 窗口,您需要执行以下操作:

2.1)选择包含您将在其中转换为pdf的文档的文件夹 源文件文件夹 部分;
2.2选择 将docx转换成pdf 来自 格式转换 下拉列表;
2.3)默认情况下, 目标路径与源相同 框被选中。 如果要将所有转换后的pdf文件放置在同一文件夹中,只需选中此选项即可;
如果要分开pdf文件和源文档,则需要取消选中 目标路径与源相同 框,然后选择一个新文件夹将pdf文件保存在 存到 框;
2.4)点击 Start 开始 按钮。 看截图:

3.然后弹出一个对话框,告诉您已成功转换了多少文档,单击 OK 按钮并关闭 文件格式转换器 窗口。

现在,所有.docx格式的文档都将转换为pdf文件。

如果您想免费试用该实用程序,请转到 免费下载软件 首先,然后按照上述步骤进行操作。

最佳办公生产力工具

Kutools for Word - 通过 Over 提升您的文字体验 100 显着特点!

🤖 Kutools 人工智能助手:用人工智能改变你的写作 - 生成内容  /  重写文本  /  总结文件  /  查询资料 基于文档,全部在Word中

📘 文档掌握: 分页  /  合并文件  /  以各种格式导出选择(PDF/TXT/DOC/HTML...)  /  批量转换为PDF  /  将页面导出为图像  /  一次打印多个文件...

内容编辑: 批量查找和替换 跨多个文件  /  调整所有图片的大小  /  转置表行和列  /  将表格转换为文字...

🧹 轻松清洁: 移开 多余的空间  /  分节符  /  所有标题  /  文本框  /  超链接  / 如需更多拆卸工具,请前往我们的 删除组...

创意插入: 插 千位分隔符  /  复选框  /  单选按钮  /  扫码支付  /  条码  /  对角线表  /  公式标题  /  图片说明  /  表标题  /  多张图片  / 发现更多 插入组...

🔍 精准选择:精确定位 特定页面  /    /  形状  /  标题段落  / 增强导航功能 更多 选择功能...

星级增强: 快速导航至任何位置  /  自动插入重复文本  /  在文档窗口之间无缝切换  /  11 转换工具...

👉 想尝试这些功能吗? Kutools for Word 提供了 60-day免费试用,没有任何限制! 🚀
 
Comments (36)
Rated 5 out of 5 · 3 ratings
This comment was minimized by the moderator on the site
Just found this, very helpful. Also thanks for the suggested mods above. I am struggling with the following:

If ((Right(xFileName, 4)) <> ".doc" Or Right(xFileName, 4) <> ".docx") Then


It seems to ask to do the conversion if it's not a doc or docx? (Leaving aside that, I think, for docx it should be last 5 chars, not 4?) Anyway,
This comment was minimized by the moderator on the site
the code stopped. I clicked debug. code below was highlighed yellow

Please, any assistance? thank you

Documents.Open Filename:=xFolder & xFileName, _
ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
wdOpenFormatAuto, XMLTransform:=""
This comment was minimized by the moderator on the site
Thank you for this. It has just saved me so much time and provided education. I will peruse your site for more top tips.
Thank you again. Brilliant quick fix. One does have to ask, why do MS make such things so impossible to find in their products.
Rated 5 out of 5
This comment was minimized by the moderator on the site
Здравствуйте! Огромное спасибо за модуль! Но есть проблема, у меня куча папок и в каждой папке больше двухсот файлов с разными именами.. Можно ли сделать так чтобы ваш модуль сохранял файлы в PDF не под номерами 1,2,3... и т.д, а под своими собственными именами файлов!? Помогите пожалуйста, и я буду молиться за вас ВЕЧНО!!))
This comment was minimized by the moderator on the site
Hi Егор,
I don't quite understand your question. After converting the file using the VBA code, the name of the PDF file is the same as the name of the Word file.
This comment was minimized by the moderator on the site
Здравствуйте! Большое спасибо вам, за то что вы есть! Спасибо за код он почти идеальный, но ОЧЕНЬ прошу Вас помочь с одним нюансом... Мне Очень важно чтоб ваш макрос сохранял в PDF не под номерами 1.2.3 и т.д, а брал название вордовского файла и сохранял под ним. У меня сто папок и в каждой по 251 файл со своим собственным названием... Мне это Очень нужно, пожалуйста помогите!?????.....
This comment was minimized by the moderator on the site
The VBA macro worked like a charm! :D
Rated 5 out of 5
This comment was minimized by the moderator on the site
Hi Myles,
Thank you for your feedback.
This comment was minimized by the moderator on the site
Hello is there a way to select a different output folder and not the original folder?

thank you
This comment was minimized by the moderator on the site
Hi Vincent,
Please try the following VBA code. After running the code, an Open window pops up, please select a folder containing the douments you want to convert, in the second popping up Save PDF files in window, select a folder to save the PDF files.

Sub ConvertWordsToPdfs()
'Updated by Extendoffice 20220805
  Dim xIndex As String
  Dim xDlg As FileDialog, xSaveDlg As FileDialog
  Dim xFolder As Variant, xSaveFolder As Variant
  Dim xNewName As String
  Dim xFileName As String
  On Error Resume Next
  Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
  xDlg.Title = "Open"
  xDlg.ButtonName = "Open"
  If xDlg.Show <> -1 Then Exit Sub
  xFolder = xDlg.SelectedItems(1) + "\"
  xFileName = Dir(xFolder & "*.*", vbNormal)
  Set xSaveDlg = Application.FileDialog(msoFileDialogFolderPicker)
  xSaveDlg.Title = "Save PDF files in"
  xSaveDlg.ButtonName = "Save"
  If xSaveDlg.Show <> -1 Then Exit Sub
  xSaveFolder = xSaveDlg.SelectedItems(1) + "\"
  Application.DisplayAlerts = wdAlertsNone
  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:=xSaveFolder & 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 wdSaveChanges
      End If
      xFileName = Dir()
  Wend
  Application.DisplayAlerts = wdAlertsAll
  Set xDlg = Nothing
  Set xSaveDlg = Nothing
End Sub
This comment was minimized by the moderator on the site
The code does not convert my Word files
This comment was minimized by the moderator on the site
This code is amazing and fast but if there is a link in the Doc file it will open a window stating there may be information linked to another file apply these changes? and then another asking to save as. Is there a way to add to the code to automatically do these steps for me? Out of ~800 there are ~40 and I must be present and do this every time.
thank you
Rated 5 out of 5
This comment was minimized by the moderator on the site
Hi Vincent,
The following VBA code can do you a favor. Please give it a try. Thank you for your feedback.

Sub ConvertWordsToPdfs()
'Updated by Extendoffice 20220805
  Dim xIndex As String
  Dim xDlg As FileDialog
  Dim xFolder As Variant
  Dim xNewName As String
  Dim xFileName As String
  On Error Resume Next
  Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
  If xDlg.Show <> -1 Then Exit Sub
  xFolder = xDlg.SelectedItems(1) + "\"
  xFileName = Dir(xFolder & "*.*", vbNormal)
  Application.DisplayAlerts = wdAlertsNone
  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 wdSaveChanges
      End If
      xFileName = Dir()
  Wend
  Application.DisplayAlerts = wdAlertsAll
End Sub
This comment was minimized by the moderator on the site
Вот тут во втором условии надо 4 заменить на 5:
If ((Right(xFileName, 4)) <> ".doc" Or Right(xFileName, 5) <> ".docx") Then
Для исключения проблемы наличия точек можно сделать так:
xIndex = InStr(xFileName, ".doc") + 1
Ну и про советы других товарищей не забыть ;)

This comment was minimized by the moderator on the site
Thank you so much! Saved me so much time!
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations