Vai al contenuto principale

Come convertire in batch più documenti Word in file PDF?

È facile convertire un documento Word in un file PDF con la funzione Salva come in Word. Ma se vuoi convertire tutti i documenti di Word in una cartella in file PDF separati contemporaneamente, come puoi ottenerlo? Questo articolo ti mostrerà un codice VBA per convertire in batch più documenti Word in file pdf in Word.

Batch converte più documenti Word in file pdf con VBA
Converti in batch più documenti Word in file PDF con Kutools per Word


Batch converte più documenti Word in file pdf con VBA

Il seguente codice VBA ti aiuta a convertire rapidamente tutti i documenti di Word in una cartella in file pdf contemporaneamente. Si prega di fare quanto segue.

1. In Word, premere il pulsante altro + F11 chiavi per aprire il Microsoft Visual Basic, Applications Edition finestra.

2. Nel Microsoft Visual Basic, Applications Edition finestra, fare clic inserire > Moduli, quindi copia sotto il codice VBA nella finestra del modulo.

Codice VBA: converte in batch più documenti Word in file PDF in 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. premi il F5 chiave per eseguire il codice.

4. Viene visualizzata una finestra di dialogo Sfoglia, selezionare la cartella che contiene i documenti di Word da convertire in file PDF e fare clic su OK pulsante.

Quindi tutti i documenti di Word nella cartella selezionata vengono convertiti in file PDF separati contemporaneamente. Vedi screenshot:


Converti in batch più documenti Word in file PDF con Kutools per Word

Se il codice VBA è difficile da gestire, puoi provare il file Converti documenti utilità di Kutools for Word per risolvere il problema.

Kutools for Word : Con oltre 100 utili componenti aggiuntivi di Word, libero di provare senza limitazioni 60 giorni.

1. Clic Kutools Plus > Doc / Docx. Vedi screenshot:

2. Nel Convertitore formato documento finestra, devi fare come segue:

2.1) Seleziona la cartella contenente i documenti che convertirai in pdf nel file Cartella del file di origine sezione;
2.2 Selezionare Converti docx in pdf dal Formato Converti menu `A tendina;
2.3) Per impostazione predefinita, il file Percorso di destinazione uguale all'origine la casella è selezionata. Se vuoi posizionare tutti i file pdf convertiti nella stessa cartella, tieni selezionata questa opzione;
Se vuoi separare i file pdf dai documenti di origine, devi deselezionare il file Percorso di destinazione uguale all'origine casella e seleziona una nuova cartella per salvare i file pdf nel file Salvare scatola;
2.4) Fare clic su Inizio pulsante. Vedi screenshot:

3. Quindi viene visualizzata una finestra di dialogo per indicare quanti documenti sono stati convertiti correttamente, fare clic su OK e chiudere il Convertitore formato documento finestra.

Ora tutti i documenti in formato .docx vengono convertiti in file pdf.

Se vuoi avere una prova gratuita di questa utility, vai su scarica gratuitamente il software prima, quindi vai ad applicare l'operazione secondo i passaggi precedenti.

I migliori strumenti per la produttività in ufficio

Kutools for Word - Migliora la tua esperienza con le parole con Over 100 Caratteristiche notevoli!

🤖 Assistente AI di Kutools: Trasforma la tua scrittura con l'intelligenza artificiale - Genera contenuto  /  Riscrivere il testo  /  Riepilogare i documenti  /  Richiedi informazioni sulla base del documento, tutto all'interno di Word

📘 Padronanza dei documenti: Pagine divise  /  Unisci documenti  /  Esporta la selezione in vari formati (PDF/TXT/DOC/HTML...)  /  Converti in batch in PDF  /  Esporta pagine come immagini  /  Stampa più file contemporaneamente...

Modifica dei contenuti: Trova e sostituisci in batch su più file  /  Ridimensiona tutte le immagini  /  Trasporre righe e colonne della tabella  /  Converti tabella in testo...

🧹 Pulito senza sforzo: Spazza via Spazi extra  /  Interruzioni di sezione  /  Tutte le intestazioni  /  Caselle di testo  /  Collegamenti ipertestuali  / Per ulteriori strumenti di rimozione, vai al nostro Rimuovi gruppo...

Inserti creativi: Inserisci Mille separatori  /  Caselle di controllo  /  Pulsanti di scelta  /  QR Code  /  Codice a barre  /  Tabella della linea diagonale  /  Didascalia dell'equazione  /  Didascalia immagine  /  Didascalia  /  Immagini multiple  / Scopri di più nella Inserisci gruppo...

???? Selezioni di precisione: Individuare pagine specifiche  /  con tabelle  /  forme  /  paragrafi di intestazione  / Migliora la navigazione con Scopri di più Seleziona funzionalità...

Miglioramenti delle stelle: Naviga rapidamente verso qualsiasi luogo  /  inserire automaticamente testo ripetitivo  /  passare senza problemi da una finestra all'altra del documento  /  11 strumenti di conversione...

👉 Vuoi provare queste funzionalità? Kutools per Word offre a Prova gratuita 60-day, senza limitazioni! 🚀
 
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