Loncat ke daftar isi utama

Bagaimana cara batch mengkonversi beberapa dokumen Word ke file pdf?

Sangat mudah bagi Anda untuk mengonversi dokumen Word menjadi file PDF dengan fungsi Simpan sebagai di Word. Tetapi jika Anda ingin mengonversi semua dokumen Word dalam folder untuk memisahkan file PDF sekaligus, bagaimana Anda bisa mencapainya? Artikel ini akan menunjukkan kepada Anda kode VBA untuk mengonversi banyak dokumen Word menjadi file pdf di Word.

Batch mengonversi beberapa dokumen Word ke file pdf dengan VBA
Batch mengonversi beberapa dokumen Word ke file pdf dengan Kutools for Word


Batch mengonversi beberapa dokumen Word ke file pdf dengan VBA

Kode VBA berikut membantu Anda dengan cepat mengonversi semua dokumen Word dalam folder ke file pdf sekaligus. Silakan lakukan sebagai berikut.

1. Di Word, tekan lain + F11 kunci untuk membuka Microsoft Visual Basic untuk Aplikasi jendela.

2. Dalam Microsoft Visual Basic untuk Aplikasi window, klik Menyisipkan > Modul, lalu salin kode VBA di bawah ini ke jendela Modul.

Kode VBA: Batch mengkonversi beberapa dokumen Word ke file pdf di 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. tekan F5 kunci untuk menjalankan kode.

4. Dialog Jelajah akan muncul, pilih folder yang berisi dokumen Word yang akan Anda ubah ke file pdf, dan klik OK .

Kemudian semua dokumen Word di folder yang dipilih diubah menjadi file pdf yang terpisah sekaligus. Lihat tangkapan layar:


Batch mengonversi beberapa dokumen Word ke file pdf dengan Kutools for Word

Jika kode VBA sulit ditangani, Anda dapat mencoba Konversi dokumen kegunaan Kutools for Word untuk memecahkan masalah.

Kutools for Word : Dengan lebih dari 100 add-in Word yang praktis, bebas untuk mencoba tanpa batasan dalam 60 hari-hari.

1. klik Kutools Ditambah > Doc / Docx. Lihat tangkapan layar:

2. Dalam Pengonversi Format Dokumen jendela, Anda perlu melakukan hal berikut:

2.1) Pilih folder berisi dokumen yang akan Anda konversi ke pdf di Folder file sumber bagian;
2.2 Pilih Konversi docx ke pdf dari Konversi Format daftar drop-down;
2.3) Secara default, file Jalur tujuan sama dengan sumber kotak dicentang. Jika Anda ingin menempatkan semua file pdf yang telah dikonversi di folder yang sama, biarkan opsi ini tetap dipilih;
Jika Anda ingin memisahkan file pdf dan dokumen sumber, Anda perlu menghapus centang Jalur tujuan sama dengan sumber kotak, dan pilih folder baru untuk menyimpan file pdf di Simpan ke kotak;
2.4) Klik Start tombol. Lihat tangkapan layar:

3. Kemudian sebuah kotak dialog muncul untuk memberitahu Anda berapa banyak dokumen yang telah berhasil diubah, klik OK tombol dan tutup Pengonversi Format Dokumen jendela.

Sekarang semua dokumen berformat .docx dikonversi ke file pdf.

Jika Anda ingin mencoba utilitas ini secara gratis, buka unduh perangkat lunak gratis pertama, lalu lanjutkan untuk menerapkan operasi sesuai langkah di atas.

Alat Produktivitas Kantor Terbaik

Kutools for Word - Tingkatkan Pengalaman Kata Anda dengan Over 100 Fitur Luar Biasa!

🤖 Asisten AI Kutools: Ubah tulisan Anda dengan AI - Hasilkan Konten  /  Menulis Ulang Teks  /  Meringkas Dokumen  /  Menanyakan Informasi berdasarkan Dokumen, semuanya dalam Word

📘 Penguasaan Dokumen: Halaman Terpisah  /  Gabungkan Dokumen  /  Ekspor Pilihan dalam Berbagai Format (PDF/TXT/DOC/HTML...)  /  Konversi Batch ke PDF  /  Ekspor Halaman sebagai Gambar  /  Cetak Banyak File sekaligus...

Pengeditan Isi: Temukan dan Ganti Batch di Banyak File  /  Ubah Ukuran Semua Gambar  /  Ubah Urutan Baris dan Kolom Tabel  /  Ubah Tabel menjadi Teks...

🧹 Bersih dengan Mudah: Menyapu Spasi Ekstra  /  Bagian Istirahat  /  Semua Header  /  Teks box  /  Hyperlink  / Untuk alat penghapus lainnya, kunjungi kami Hapus Grup...

Sisipan Kreatif: Memasukkan Seribu Pemisah  /  Kotak Centang  /  Tombol Radio  /  Kode QR  /  barcode  /  Tabel Garis Diagonal  /  Keterangan Persamaan  /  Keterangan gambar  /  Keterangan Tabel  /  Banyak Gambar  / Temukan lebih lanjut di Sisipkan Grup...

🔍 Pilihan Presisi: Tepat halaman tertentu  /  tabel  /  bentuk  /  paragraf judul  / Tingkatkan navigasi dengan lebih Pilih fitur...

Peningkatan Bintang: Navigasi dengan cepat ke lokasi mana pun  /  menyisipkan teks berulang secara otomatis  /  beralih antar jendela dokumen dengan mulus  /  11 Alat Konversi...

👉 Ingin mencoba fitur-fitur tersebut? Kutools for Word menawarkan a Uji coba gratis 60-hari, tanpa batasan! 🚀
 
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