Saltar al contenido principal

¿Cómo convertir por lotes varios documentos de Word a archivos pdf?

Es fácil para usted convertir un documento de Word en un archivo PDF con la función Guardar como en Word. Pero si desea convertir todos los documentos de Word en una carpeta en archivos PDF separados a la vez, ¿cómo puede lograrlo? Este artículo le mostrará un código VBA para convertir por lotes varios documentos de Word a archivos PDF en Word.

Convierta por lotes varios documentos de Word a archivos pdf con VBA
Convierta por lotes varios documentos de Word a archivos pdf con Kutools para Word


Convierta por lotes varios documentos de Word a archivos pdf con VBA

El siguiente código VBA lo ayuda a convertir rápidamente todos los documentos de Word en una carpeta a archivos PDF a la vez. Haz lo siguiente.

1. En Word, presione el otro + F11 teclas para abrir el Microsoft Visual Basic para aplicaciones ventana.

2. En el Microsoft Visual Basic para aplicaciones ventana, haga clic recuadro > Módulo, luego copie el código de VBA a continuación en la ventana del Módulo.

Código VBA: convierta por lotes varios documentos de Word a archivos pdf en 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. presione el F5 clave para ejecutar el código.

4. Aparecerá un cuadro de diálogo Examinar, seleccione la carpeta que contiene los documentos de Word que convertirá a archivos pdf y haga clic en OK del botón.

Luego, todos los documentos de Word en la carpeta seleccionada se convierten en archivos PDF separados a la vez. Ver captura de pantalla:


Convierta por lotes varios documentos de Word a archivos pdf con Kutools para Word

Si el código VBA es difícil de manejar, puede probar el Convertir documentos utilidad de Kutools for Word para resolver el problema.

Kutools for Word : Con más de 100 útiles complementos de Word, libre de probar sin limitación en 60 días.

1. Hacer clic en Kutools Más > Doc / Docx. Ver captura de pantalla:

2. En el Convertidor de formato de documento ventana, debe hacer lo siguiente:

2.1) Seleccione la carpeta que contiene los documentos que convertirá a pdf en el Carpeta de archivo de origen sección;
2.2 Select Convertir docx a pdf del desplegable Formato Convertir la lista desplegable;
2.3) Por defecto, el Ruta de destino igual que la fuente la casilla está marcada. Si desea colocar todos los archivos PDF convertidos en la misma carpeta, mantenga esta opción seleccionada;
Si desea separar los archivos pdf y los documentos de origen, debe desmarcar la Ruta de destino igual que la fuente cuadro y seleccione una nueva carpeta para guardar los archivos PDF en el Guardar en... caja;
2.4) Haga clic en Inicio botón. Ver captura de pantalla:

3. Luego aparece un cuadro de diálogo para indicarle cuántos documentos se han convertido correctamente, haga clic en el OK botón y cierre el Convertidor de formato de documento ventana.

Ahora todos los documentos en formato .docx se convierten a archivos pdf.

Si desea tener una prueba gratuita de esta utilidad, vaya a descarga gratis el software primero, y luego vaya a aplicar la operación según los pasos anteriores.

Las mejores herramientas de productividad de oficina

Kutools for Word - Mejore su experiencia con Word con Over 100 ¡Características notables!

🤖 Asistente de IA de Kutools: Transforma tu escritura con IA - Generar contenido  /  Reescribir texto  /  Resumir documentos  /  Solicite información basado en el documento, todo dentro de Word

📘 Dominio del documento: Dividir páginas  /  Combinar documentos  /  Exportar selección en varios formatos (PDF/TXT/DOC/HTML...)  /  Convertir por lotes a PDF  /  Exportar páginas como imágenes  /  Imprima varios archivos a la vez...

Edición de contenidos: Buscar y reemplazar por lotes en varios archivos  /  Cambiar el tamaño de todas las imágenes  /  Transponer filas y columnas de tabla  /  Convertir tabla en texto...

🧹 Limpieza sin esfuerzo: barrer Espacios extra  /  Saltos de sección  /  Todos los encabezados  /  Cuadros de texto  /  Los hipervínculos  / Para obtener más herramientas de extracción, diríjase a nuestro Quitar grupo...

Inserciones creativas: Insertar Mil Separadores  /  Casillas de verificación  /  Botones de radio  /  Código QR   /  Barcode  /  Tabla de líneas diagonales  /  Título de la ecuación  /  Captura de imagen  /  Pie de tabla  /  Varias imágenes  / Descubre más en el Insertar grupo...

🔍 Selecciones de precisión: Localizar páginas específicas  /  tablas  /  formas  /  párrafos de encabezado  / Mejorar la navegación con más, Seleccionar características...

Mejoras de estrellas: Navegue rápidamente a cualquier ubicación  /  insertar automáticamente texto repetitivo  /  alternar sin problemas entre ventanas de documentos  /  11 herramientas de conversión...

👉 ¿Quieres probar estas funciones? Kutools para Word ofrece una prueba gratuita de 60 días.¡Sin limitaciones! 🚀
 
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