Przejdź do głównej zawartości

Jak wsadowo konwertować wiele dokumentów Word na pliki PDF?

Konwersja dokumentu programu Word do pliku PDF jest łatwa dzięki funkcji Zapisz jako w programie Word. Ale jeśli chcesz przekonwertować wszystkie dokumenty programu Word w folderze na osobne pliki PDF naraz, jak możesz to osiągnąć? W tym artykule pokażemy kod VBA do wsadowej konwersji wielu dokumentów Word na pliki PDF w programie Word.

Batch konwertuje wiele dokumentów Word na pliki PDF za pomocą VBA
Batch konwertuj wiele dokumentów Word na pliki PDF za pomocą Kutools for Word


Batch konwertuje wiele dokumentów Word na pliki PDF za pomocą VBA

Poniższy kod VBA pomaga szybko przekonwertować wszystkie dokumenty programu Word w folderze na pliki PDF jednocześnie. Wykonaj następujące czynności.

1. W programie Word naciśnij inny + F11 klawisze, aby otworzyć Microsoft Visual Basic for Applications okno.

2. w Microsoft Visual Basic for Applications okno, kliknij wstawka > Moduł, a następnie skopiuj poniższy kod VBA do okna modułu.

Kod VBA: Batch konwertuje wiele dokumentów Word na pliki PDF w programie 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. wciśnij F5 klucz do uruchomienia kodu.

4. Pojawi się okno dialogowe Przeglądaj, wybierz folder zawierający dokumenty programu Word, które chcesz przekonwertować na pliki PDF, i kliknij OK przycisk.

Następnie wszystkie dokumenty programu Word w wybranym folderze są od razu konwertowane na oddzielne pliki PDF. Zobacz zrzut ekranu:


Batch konwertuj wiele dokumentów Word na pliki PDF za pomocą Kutools for Word

Jeśli kod VBA jest trudny w obsłudze, możesz wypróbować Konwertuj dokumenty użyteczność Kutools dla Worda rozwiązać problem.

Kutools dla Worda : Ponad 100 przydatnych dodatków do Worda, za darmo spróbować bez ograniczeń w 60 dni.

1. kliknij Kutools Plus > Doc / Docx. Zobacz zrzut ekranu:

2. w Konwerter formatów dokumentów okno, musisz wykonać następujące czynności:

2.1) Wybierz folder zawierający dokumenty, które przekonwertujesz do formatu PDF w formacie Folder plików źródłowych Sekcja;
2.2 Wybierz Konwertuj docx na pdf z Format Konwertuj Lista rozwijana;
2.3) Domyślnie Ścieżka docelowa taka sama jak źródło pole jest zaznaczone. Jeśli chcesz umieścić wszystkie przekonwertowane pliki PDF w tym samym folderze, po prostu pozostaw tę opcję zaznaczoną;
Jeśli chcesz oddzielić pliki PDF i dokumenty źródłowe, musisz odznaczyć Ścieżka docelowa taka sama jak źródło i wybierz nowy folder, aby zapisać pliki pdf w formacie Zapisz do pudełko;
2.4) Kliknij Start przycisk. Zobacz zrzut ekranu:

3. Następnie pojawi się okno dialogowe z informacją, ile dokumentów zostało pomyślnie przekonwertowanych, kliknij OK i zamknij Konwerter formatów dokumentów okno.

Teraz wszystkie dokumenty w formacie .docx są konwertowane na pliki pdf.

Jeśli chcesz skorzystać z bezpłatnej wersji próbnej tego narzędzia, przejdź do bezpłatnie pobrać oprogramowanie najpierw, a następnie przejdź do wykonania operacji zgodnie z powyższymi krokami.

Najlepsze narzędzia biurowe

Kutools dla Worda - Podnieś swoje doświadczenie ze słowami dzięki Over 100 Niezwykłe funkcje!

🤖 Kutools Asystent AI: Zmień swoje pisanie dzięki AI - Generuj zawartość  /  Przepisz tekst  /  Podsumowanie dokumentów  /  Zapytaj o informacje na podstawie Dokumentu, wszystko w programie Word

📘 Znajomość dokumentów: Podziel strony  /  Scal dokumenty  /  Eksportuj zaznaczenie w różnych formatach (PDF/TXT/DOC/HTML...)  /  Wsadowa konwersja do formatu PDF  /  Eksportuj strony jako obrazy  /  Drukuj wiele plików jednocześnie...

Edycja treści: Znajdź i zamień partii w wielu plikach  /  Zmień rozmiar wszystkich zdjęć  /  Transponuj wiersze i kolumny tabeli  /  Konwertuj tabelę na tekst...

🧹 Łatwe czyszczenie: Wymień Dodatkowe przestrzenie  /  Podziały sekcji  /  Wszystkie nagłówki  /  Pola tekstowe  /  Hiperłącza  / Więcej narzędzi do usuwania znajdziesz na naszej stronie Usuń grupę...

Kreatywne wstawki: Wstawić Tysiące separatorów  /  Pola wyboru  /  Przyciski Radio  /  Kod QR  /  kod kreskowy  /  Tabela linii ukośnych  /  Podpis równania  /  Tytuł Zdjęcia  /  Podpis tabeli  /  Wiele zdjęć  / Odkryj więcej w Wstaw grupę...

🔍 Precyzyjne wybory: Punktowy konkretne strony  /  stoły  /  kształty  /  nagłówki akapitów  / Ulepsz nawigację za pomocą jeszcze Wybierz funkcje...

Ulepszenia gwiazd: Nawiguj szybko do dowolnej lokalizacji  /  automatyczne wstawianie powtarzającego się tekstu  /  płynnie przełączaj się pomiędzy oknami dokumentów  /  11 Narzędzia konwersji...

???? Chcesz wypróbować te funkcje? Kutools dla Word oferuje Bezpłatna wersja próbna 60-day, bez ograniczeń! 🚀
 
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