Passer au contenu principal

Comment convertir par lots plusieurs documents Word en fichiers PDF?

Il est facile pour vous de convertir un document Word en fichier PDF avec la fonction Enregistrer sous de Word. Mais si vous souhaitez convertir tous les documents Word d'un dossier en fichiers PDF séparés en même temps, comment pouvez-vous y parvenir? Cet article vous montrera un code VBA pour convertir par lots plusieurs documents Word en fichiers PDF dans Word.

Conversion par lots de plusieurs documents Word en fichiers PDF avec VBA
Convertissez par lots plusieurs documents Word en fichiers PDF avec Kutools for Word


Conversion par lots de plusieurs documents Word en fichiers PDF avec VBA

Le code VBA suivant vous aide à convertir rapidement tous les documents Word d'un dossier en fichiers PDF à la fois. Veuillez faire comme suit.

1. Dans Word, appuyez sur le autre + F11 clés pour ouvrir le Microsoft Visual Basic pour applications fenêtre.

2. dans le Microsoft Visual Basic pour applications fenêtre, cliquez sur insérer > Module, puis copiez ci-dessous le code VBA dans la fenêtre Module.

Code VBA: convertir par lots plusieurs documents Word en fichiers PDF dans 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. appuie sur le F5 clé pour exécuter le code.

4. Une boîte de dialogue Parcourir apparaît, sélectionnez le dossier contenant les documents Word que vous allez convertir en fichiers pdf, puis cliquez sur le bouton OK .

Ensuite, tous les documents Word du dossier sélectionné sont convertis en fichiers PDF séparés à la fois. Voir la capture d'écran:


Convertissez par lots plusieurs documents Word en fichiers PDF avec Kutools for Word

Si le code VBA est difficile à gérer, vous pouvez essayer le Convertir des documents utilité de Kutools for Word résoudre le problème.

Kutools for Word : Avec plus de 100 compléments Word pratiques, libre d'essayer sans limitation dans 60 jours.

1. Cliquez Kutools Plus > Doc / Docx. Voir la capture d'écran:

2. dans le Convertisseur de format de document fenêtre, vous devez procéder comme suit:

2.1) Sélectionnez le dossier contenant les documents que vous allez convertir en pdf dans le Dossier de fichiers source section;
2.2 Sélectionnez Convertir docx en pdf du Conversion de format la liste déroulante;
2.3) Par défaut, le Chemin de destination identique à la source la case est cochée. Si vous souhaitez placer tous les fichiers PDF convertis dans le même dossier, gardez simplement cette option sélectionnée;
Si vous souhaitez séparer les fichiers pdf et les documents source, vous devez décocher la case Chemin de destination identique à la source et sélectionnez un nouveau dossier pour enregistrer les fichiers pdf dans le Ajouter à la boîte;
2.4) Cliquez sur le Accueil bouton. Voir la capture d'écran:

3. Ensuite, une boîte de dialogue apparaît pour vous dire combien de documents ont été convertis avec succès, cliquez sur le OK et fermez le Convertisseur de format de document fenêtre.

Désormais, tous les documents au format .docx sont convertis en fichiers pdf.

Si vous souhaitez avoir un essai gratuit de cet utilitaire, rendez-vous sur télécharger gratuitement le logiciel d'abord, puis appliquez l'opération selon les étapes ci-dessus.

Meilleurs outils de productivité bureautique

Kutools for Word - Élevez votre expérience Word avec Over 100 Caractéristiques remarquables !

🤖 Assistant IA Kutools: Transformez votre écriture avec l'IA - Générer du contenu  /  Réécrire le texte  /  Résumer des documents  /  Demander des informations basé sur le document, le tout dans Word

(I.e. Maîtrise des documents: Pages divisées  /  Fusionner des documents  /  Exporter la sélection dans différents formats (PDF/TXT/DOC/HTML...)  /  Conversion par lots en PDF  /  Exporter des pages sous forme d'images  /  Imprimer plusieurs fichiers à la fois

Édition du contenu: Rechercher et remplacer par lots sur plusieurs fichiers  /  Redimensionner toutes les images  /  Transposer les lignes et les colonnes du tableau  /  Convertir le tableau en texte

🧹 Nettoyage sans effort : balayer Espaces supplémentaires  /  Sauts de section  /  Tous les en-têtes  /  Boîtes de texte  /  Liens hypertextes  / Pour plus d'outils de suppression, rendez-vous sur notre Supprimer le groupe

Insertions créatives: Insérer Mille séparateurs  /  Cases à cocher  /  Boutons radio  /  code QR  /  Code barres  /  Tableau des lignes diagonales  /  Légende de l'équation  /  Légende  /  Légende de la table  /  Plusieurs images  / Découvrez-en davantage dans le Insérer un groupe

🔍 Sélections de précision: Localiser pages spécifiques  /  les tables  /  formes  /  paragraphes de titre  / Améliorez la navigation avec PLUS Sélectionnez les fonctionnalités

Améliorations des étoiles: Naviguez rapidement vers n’importe quel endroit  /  insertion automatique de texte répétitif  /  basculer de manière transparente entre les fenêtres de document  /  11 outils de conversion

👉 Vous voulez essayer ces fonctionnalités ? Kutools for Word propose un Essai gratuit 60-day, sans aucune limite ! 🚀
 
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