Bỏ qua nội dung chính

Làm thế nào để chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf?

Bạn có thể dễ dàng chuyển đổi tài liệu Word sang tệp PDF với chức năng Save as trong Word. Nhưng nếu bạn muốn chuyển đổi tất cả các tài liệu Word trong một thư mục để tách các tệp PDF cùng một lúc, làm thế nào bạn có thể đạt được điều đó? Bài viết này sẽ chỉ cho bạn một mã VBA để chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf trong Word.

Chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf với VBA
Chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf với Kutools cho Word


Chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf với VBA

Đoạn mã VBA sau đây giúp bạn nhanh chóng chuyển đổi tất cả các tài liệu Word trong một thư mục sang tệp pdf cùng một lúc. Hãy làm như sau.

1. Trong Word, nhấn Khác + F11 phím để mở Microsoft Visual Basic cho các ứng dụng cửa sổ.

2. bên trong Microsoft Visual Basic cho các ứng dụng cửa sổ, nhấp Chèn > Mô-đun, sau đó sao chép mã VBA bên dưới vào cửa sổ Mô-đun.

Mã VBA: Chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf trong Word

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. Nhấn nút F5 phím để chạy mã.

4. Hộp thoại Duyệt hiện lên, vui lòng chọn thư mục chứa tài liệu Word bạn sẽ chuyển đổi sang tệp pdf và nhấp vào OK .

Sau đó, tất cả các tài liệu Word trong thư mục đã chọn được chuyển đổi thành các tệp pdf riêng biệt cùng một lúc. Xem ảnh chụp màn hình:


Chuyển đổi hàng loạt nhiều tài liệu Word sang tệp pdf với Kutools cho Word

Nếu khó xử lý mã VBA, bạn có thể thử Chuyển đổi tài liệu tiện ích của Kutools cho Word để giải quyết vấn đề.

Kutools cho Word : Với hơn 100 phần bổ trợ Word tiện dụng, miễn phí để thử mà không có giới hạn trong 60 ngày.

1. nhấp chuột Kutools Plus > Doc / Docx. Xem ảnh chụp màn hình:

2. bên trong Công cụ chuyển đổi định dạng tài liệu cửa sổ, bạn cần làm như sau:

2.1) Chọn thư mục chứa các tài liệu bạn sẽ chuyển đổi sang pdf trong Thư mục tệp nguồn phần;
2.2 Chọn Chuyển đổi docx sang pdf từ Chuyển đổi định dạng danh sách thả xuống;
2.3) Theo mặc định, Đường dẫn đích giống với nguồn hộp được chọn. Nếu bạn muốn đặt tất cả các tệp pdf đã chuyển đổi trong cùng một thư mục, chỉ cần chọn tùy chọn này;
Nếu bạn muốn tách các tệp pdf và tài liệu nguồn, bạn cần bỏ chọn Đường dẫn đích giống với nguồn và chọn một thư mục mới để lưu các tệp pdf trong Lưu vào cái hộp;
2.4) Nhấp vào Bắt đầu cái nút. Xem ảnh chụp màn hình:

3. Sau đó, một hộp thoại bật lên cho bạn biết có bao nhiêu tài liệu đã được chuyển đổi thành công, hãy nhấp vào OK nút và đóng Công cụ chuyển đổi định dạng tài liệu cửa sổ.

Bây giờ tất cả các tài liệu định dạng .docx đều được chuyển đổi thành tệp pdf.

Nếu bạn muốn dùng thử miễn phí tiện ích này, vui lòng truy cập tải xuống miễn phí phần mềm đầu tiên, và sau đó đi đến áp dụng hoạt động theo các bước trên.

Công cụ năng suất văn phòng tốt nhất

Kutools cho Word - Nâng cao trải nghiệm sử dụng từ của bạn với Over 100 Các tính năng đáng chú ý!

🤖 Trợ lý AI của Kutools: Biến đổi bài viết của bạn bằng AI - Tạo nội dung  /  Viết lại văn bản  /  Tóm tắt tài liệu  /  Hỏi thông tin dựa trên tài liệu, tất cả đều có trong Word

📘 Làm chủ tài liệu: Chia trang  /  Hợp nhất tài liệu  /  Lựa chọn xuất khẩu ở nhiều định dạng khác nhau (PDF/TXT/DOC/HTML...)  /  Chuyển đổi hàng loạt sang PDF  /  Xuất trang dưới dạng hình ảnh  /  In nhiều tập tin cùng một lúchữu ích. Cảm ơn !

Chỉnh sửa nội dung: Tìm và thay thế hàng loạt trên nhiều tệp  /  Thay đổi kích thước tất cả hình ảnh  /  Hoán đổi hàng và cột của bảng  /  Chuyển bảng thành văn bảnhữu ích. Cảm ơn !

🧹 Dễ dàng làm sạch: Quét đi Không gian bổ sung  /  Phần ngắt  /  Tất cả các tiêu đề  /  Hộp văn bản  /  Các siêu liên kết  / Để biết thêm các công cụ xóa, hãy truy cập Xóa nhómhữu ích. Cảm ơn !

Phụ trang quảng cáo: Chèn Ngàn dấu phân cách  /  Hộp kiểm tra  /  Nút radio  /  Mã QR  /  Mã vạch  /  Bảng đường chéo  /  Chú thích phương trình  /  Hình ảnh Caption  /  Bảng chú thích  /  Nhiều Hình Ảnh  / Khám phá thêm trong Chèn nhómhữu ích. Cảm ơn !

???? Lựa chọn chính xác: Xác định trang cụ thể  /  bảng  /  hình dạng  /  đoạn văn tiêu đề  / Tăng cường điều hướng với chi tiết Chọn tính nănghữu ích. Cảm ơn !

Cải tiến sao: Điều hướng nhanh chóng đến bất kỳ vị trí nào  /  tự động chèn văn bản lặp đi lặp lại  /  chuyển đổi liền mạch giữa các cửa sổ tài liệu  /  11 công cụ chuyển đổihữu ích. Cảm ơn !

👉 Bạn muốn thử những tính năng này? Kutools cho Word cung cấp một 60 ngày dùng thử miễn phí, không có giới hạn! 🚀
 
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