Note: The other languages of the website are Google-translated. Back to English
Iniciar  \/ 
x
or
x
Registrarse  \/ 
x

or

¿Cómo contar los números de página de los archivos PDF en Excel?

Si hay varios archivos PDF en una carpeta específica, ahora desea mostrar todos estos nombres de archivo en una hoja de trabajo y obtener los números de página de cada archivo. ¿Cómo podría hacer frente a este trabajo en Excel de forma rápida y sencilla?

Cuente los números de página de los archivos PDF de una carpeta en la hoja de trabajo con código VBA


Cuente los números de página de los archivos PDF de una carpeta en la hoja de trabajo con código VBA

Puede ser que el siguiente código VBA pueda ayudarlo a mostrar todos los nombres de archivos PDF y sus números de página en una hoja de trabajo, haga lo siguiente:

1. Abra una hoja de trabajo donde desee obtener los archivos PDF y los números de página.

2. Mantenga pulsado el ALT + F11 llaves, y abre el Microsoft Visual Basic para aplicaciones ventana.

3. Hacer clic recuadro > Móduloy pegue la siguiente macro en el Módulo Ventana.

Código de VBA: enumere todos los nombres de archivos PDF y números de página en la hoja de trabajo:

Sub Test()
    Dim I As Long
    Dim xRg As Range
    Dim xStr As String
    Dim xFd As FileDialog
    Dim xFdItem As Variant
    Dim xFileName As String
    Dim xFileNum As Long
    Dim RegExp As Object
    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    If xFd.Show = -1 Then
        xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
        xFileName = Dir(xFdItem & "*.pdf", vbDirectory)
        Set xRg = Range("A1")
        Range("A:B").ClearContents
        Range("A1:B1").Font.Bold = True
        xRg = "File Name"
        xRg.Offset(0, 1) = "Pages"
        I = 2
        xStr = ""
        Do While xFileName <> ""
            Cells(I, 1) = xFileName
            Set RegExp = CreateObject("VBscript.RegExp")
            RegExp.Global = True
            RegExp.Pattern = "/Type\s*/Page[^s]"
            xFileNum = FreeFile
            Open (xFdItem & xFileName) For Binary As #xFileNum
                xStr = Space(LOF(xFileNum))
                Get #xFileNum, , xStr
            Close #xFileNum
            Cells(I, 2) = RegExp.Execute(xStr).Count
            I = I + 1
            xFileName = Dir
        Loop
        Columns("A:B").AutoFit
    End If
End Sub

4. Después de pegar el código y luego presione F5 clave para ejecutar este código, y una Búsqueda de aparece la ventana emergente, seleccione la carpeta que contiene los archivos PDF que desea enumerar y contar los números de página, vea la captura de pantalla:

doc count pdf páginas 1

5. Y luego, haga clic en OK , todos los nombres de archivos PDF y números de página se enumeran en la hoja de trabajo actual, vea la captura de pantalla:

doc count pdf páginas 2


Las mejores herramientas de productividad de oficina

Kutools para Excel resuelve la mayoría de sus problemas y aumenta su productividad en un 80%

  • Reutilizar: Inserte rápidamente fórmulas complejas, gráficos y cualquier cosa que hayas usado antes; Cifrar celdas con contraseña; Crear lista de distribución y enviar correos electrónicos ...
  • Barra de súper fórmula (edite fácilmente varias líneas de texto y fórmulas); Diseño de lectura (leer y editar fácilmente un gran número de celdas); Pegar en rango filtrado...
  • Combinar celdas / filas / columnas sin perder datos; Contenido de celdas divididas; Combinar filas / columnas duplicadas... Prevenir celdas duplicadas; Comparar rangos...
  • Seleccione Duplicado o Único Filas; Seleccionar filas en blanco (todas las celdas están vacías); Super Find y Fuzzy Find en muchos libros de trabajo; Selección aleatoria ...
  • Copia exacta Varias celdas sin cambiar la referencia de la fórmula; Crear referencias automáticamente a varias hojas; Insertar viñetas, Casillas de verificación y más ...
  • Extraer texto, Agregar texto, Eliminar por posición, Quitar espacio; Crear e imprimir subtotales de paginación; Convertir entre contenido de celdas y comentarios...
  • Súper filtro (guardar y aplicar esquemas de filtros a otras hojas); Orden avanzado por mes / semana / día, frecuencia y más; Filtro especial en negrita, cursiva ...
  • Combinar libros y hojas de trabajo; Combinar tablas basadas en columnas clave; Dividir datos en varias hojas; Conversión por lotes de xls, xlsx y PDF...
  • Más de 300 potentes funciones. Compatible con Office / Excel 2007-2019 y 365. Compatible con todos los idiomas. Fácil implementación en su empresa u organización. Características completas Prueba gratuita de 30 días. Garantía de devolución de dinero de 60 días.
pestaña kte 201905

Office Tab lleva la interfaz con pestañas a Office y hace que su trabajo sea mucho más fácil

  • Habilite la edición y lectura con pestañas en Word, Excel, PowerPoint, Publisher, Access, Visio y Project.
  • Abra y cree varios documentos en nuevas pestañas de la misma ventana, en lugar de en nuevas ventanas.
  • ¡Aumenta su productividad en un 50% y reduce cientos de clics del mouse todos los días!
officetab parte inferior
Say something here...
symbols left.
You are guest
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    brent balkwill · 1 months ago
    Thanks all this code was very useful saved me a few hours of work to get the result manually.
  • To post as a guest, your comment is unpublished.
    LHH · 7 months ago
    Good day, I had the problem that for some versions of PDF with Word, this code gave me sometimes a multiple (like 4x) of the actual page numbers. My solution was to search a string in the PDF file that actually states the page numbers and if it can be of help for anyone, this is the sub I used:
    Function GetPDFpag(File1 As String) As Long

    Const ForReading = 1, ForWriting = 2
    Dim FSO As Object
    Dim FileIn, FileOut, strTmp, strOut, Scheck As String
    Dim Nstart, Nstop As Long
    Dim K As Long

    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set FileIn = FSO.OpenTextFile(File1, ForReading, False, 0)

    'we search for the first line with string "/Kids[" in which the number of pages is
    Scheck = "no"
    K = 1
    Do Until FileIn.AtEndOfStream Or Scheck = "yes"
    K = K + 1
    strTmp = FileIn.readline
    If Len(strTmp) > 0 Then
    If InStr(1, strTmp, "/Count", vbTextCompare) > 0 And InStr(1, strTmp, "/Kids[", vbTextCompare) > 0 Then
    strOut = strTmp
    Scheck = "yes"
    End If
    End If
    Loop

    If Scheck = "no" Then
    strOut = 0
    Else
    Nstart = InStr(strOut, "/Count") + 7
    Nstop = InStr(strOut, "/Kids")
    Nstop = Nstop - Nstart
    strOut = Mid(strOut, Nstart, Nstop)
    End If

    FileIn.Close
    'FileOut.Close

    GetPDFpag = Val(strOut)
    Set FSO = Nothing
    End Function
  • To post as a guest, your comment is unpublished.
    Robbie · 7 months ago
    Any chance this could be expanded to pull a Bates number from the first page of each pdf?
  • To post as a guest, your comment is unpublished.
    Steco · 9 months ago
    Hi Skyyang,
    First I'd like to thank you for that incredible work you do, and the time you take...
    I'm searching for a while for a VBA code :
    I Have an Excelsheet with in column "J" a list of pdf, xlsx and elm files located in a data room directory (with subdirectory's)
    File name are complete with type X:\Data_Room\Sub_directory_1\file.pdf
    The code should fill the column "I" with the number of pages of each .pdf and .xls files (no need for other, cels should stay blank)
    Could you please help me?
  • To post as a guest, your comment is unpublished.
    John · 10 months ago
    is there a way to include .doc I noticed that it works for .docx but not .doc
    • To post as a guest, your comment is unpublished.
      skyyang · 10 months ago
      Hi, John,
      To count the pages of .doc and .docx as well as the PDF files, please apply the following code:
      Sub StatisticsPage() Dim I As Long Dim xRg As Range Dim xStr As String Dim xFd As FileDialog Dim xFdItem As Variant Dim xFileName As String Dim xFileNum As Long Dim RegExp As Object Dim xWdApp Dim xWd Set xFd = Application.FileDialog(msoFileDialogFolderPicker) If xFd.Show = -1 Then Application.ScreenUpdating = False xFdItem = xFd.SelectedItems(1) & Application.PathSeparator xFileName = Dir(xFdItem & "*.pdf", vbDirectory) Set xRg = Range("A1") Range("A:B").ClearContents Range("A1:B1").Font.Bold = True xRg = "File Name" xRg.Offset(0, 1) = "Pages" I = 2 xStr = "" Do While xFileName <> "" Cells(I, 1) = xFileName Set RegExp = CreateObject("VBscript.RegExp") RegExp.Global = True RegExp.Pattern = "/Type\s*/Page[^s]" xFileNum = FreeFile Open (xFdItem & xFileName) For Binary As #xFileNum xStr = Space(LOF(xFileNum)) Get #xFileNum, , xStr Close #xFileNum Cells(I, 2) = RegExp.Execute(xStr).Count I = I + 1 xFileName = Dir Loop xFileName = Dir(xFdItem & "*.docx", vbDirectory) Set xWdApp = CreateObject("Word.Application") Do While xFileName <> "" Cells(I, 1) = xFileName xFileNum = FreeFile Set xWd = GetObject(xFdItem & xFileName) Cells(I, 2) = xWd.ActiveWindow.Panes(1).Pages.Count xWd.Close False I = I + 1 xFileName = Dir Loop xFileName = Dir(xFdItem & "*.doc", vbDirectory) Set xWdApp = CreateObject("Word.Application") Do While xFileName <> "" Cells(I, 1) = xFileName xFileNum = FreeFile Set xWd = GetObject(xFdItem & xFileName) Cells(I, 2) = xWd.ActiveWindow.Panes(1).Pages.Count xWd.Close False I = I + 1 xFileName = Dir Loop Columns("A:B").AutoFit End If Application.ScreenUpdating = True End Sub
      Please try, hope it can help you!

      • To post as a guest, your comment is unpublished.
        Vidyadhar · 1 months ago
        Thanks this helps a lots.
  • To post as a guest, your comment is unpublished.
    ThomasB · 11 months ago
    Hello,

    Is het possible to also get the dimensions of the pages and the creator of the pdf in this macro?

    can someone help me with this?
  • To post as a guest, your comment is unpublished.
    shivdin · 1 years ago
    Hello, this works really well thanks!, is it possible to get the page size for the first page of the PDF document?
  • To post as a guest, your comment is unpublished.
    shivdin@hotmail.com · 1 years ago
    Hello, this really works well, thank you. Is it possible to get the page size of the first page in a new column? example 8.5 x 11, 11 x 17 etc.

  • To post as a guest, your comment is unpublished.
    deepak · 1 years ago
    I have opened a pdf file who's path and name is mention in excel cell column "C9". I just want to get last page number in excel vba please help me


  • To post as a guest, your comment is unpublished.
    sroczeto@gmail.com · 1 years ago
    Hello, works great, thank you for sharing this. One question, is it possible to add that also counts microsoft word .doc and .docx files?
    • To post as a guest, your comment is unpublished.
      skyyang · 1 years ago
      Hi, sroczeto,
      To count the page number of .doc and .docx as well as the PDF files, please apply the following code:
      Sub Test()
      Dim I As Long
      Dim xRg As Range
      Dim xStr As String
      Dim xFd As FileDialog
      Dim xFdItem As Variant
      Dim xFileName As String
      Dim xFileNum As Long
      Dim RegExp As Object
      Dim xWdApp
      Dim xWd
      Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
      If xFd.Show = -1 Then
      Application.ScreenUpdating = False
      xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
      xFileName = Dir(xFdItem & "*.pdf", vbDirectory)
      Set xRg = Range("A1")
      Range("A:B").ClearContents
      Range("A1:B1").Font.Bold = True
      xRg = "File Name"
      xRg.Offset(0, 1) = "Pages"
      I = 2
      xStr = ""
      Do While xFileName <> ""
      Cells(I, 1) = xFileName
      Set RegExp = CreateObject("VBscript.RegExp")
      RegExp.Global = True
      RegExp.Pattern = "/Type\s*/Page[^s]"
      xFileNum = FreeFile
      Open (xFdItem & xFileName) For Binary As #xFileNum
      xStr = Space(LOF(xFileNum))
      Get #xFileNum, , xStr
      Close #xFileNum
      Cells(I, 2) = RegExp.Execute(xStr).Count
      I = I + 1
      xFileName = Dir
      Loop
      xFileName = Dir(xFdItem & "*.docx", vbDirectory)
      Set xWdApp = CreateObject("Word.Application")
      Do While xFileName <> ""
      Cells(I, 1) = xFileName
      xFileNum = FreeFile
      Set xWd = GetObject(xFdItem & xFileName)
      Cells(I, 2) = xWd.ActiveWindow.Panes(1).Pages.Count
      xWd.Close False
      I = I + 1
      xFileName = Dir
      Loop
      Columns("A:B").AutoFit
      End If
      Application.ScreenUpdating = True
      End Sub
      • To post as a guest, your comment is unpublished.
        sroczeto@gmail.com · 1 years ago
        Thanks mate! It works on pdf and docx, but not on doc files. And one question more, can yo uadd that this will count in subfolders too?
  • To post as a guest, your comment is unpublished.
    Asela · 1 years ago
    Thank you so much
  • To post as a guest, your comment is unpublished.
    Viviane · 1 years ago
    Awesome code! I cant get it to work in subfolders. Can anyone help me pleas?
  • To post as a guest, your comment is unpublished.
    JuleZz_St · 1 years ago
    Hello.

    Is there a way to also add the page number of the documents and also I get an error and this is the message:
    xStr = Space(LOF(xFileNum))


    Thank you very much.
  • To post as a guest, your comment is unpublished.
    Aleca Tesseris Sulli · 1 years ago
    oh i see, this is the whole code. I tried to add to the original and was getting an error. Thank you!
  • To post as a guest, your comment is unpublished.
    Daphne · 1 years ago
    wow. subfolders works great. can you share how to add "file path" and "file size" too?
    • To post as a guest, your comment is unpublished.
      skyyang · 1 years ago
      Hello, Daphne,
      For solving your problem, please apply the below code, please try, hope it can help you!

      Sub Test()
      Dim I As Long
      Dim xRg As Range
      Dim xStr As String
      Dim xFd As FileDialog
      Dim xFdItem As Variant
      Dim xFileName As String
      Dim xFileNum As Long
      Dim RegExp As Object
      Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
      If xFd.Show = -1 Then
      xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
      Set xRg = Range("A1")
      Range("A:B").ClearContents
      Range("A1:B1").Font.Bold = True
      xRg = "File Name"
      xRg.Offset(0, 1) = "Pages"
      xRg.Offset(0, 2) = "Path"
      xRg.Offset(0, 3) = "Size(b)"
      I = 2
      Call SunTest(xFdItem, I)
      End If
      End Sub

      Sub SunTest(xFdItem As Variant, I As Long)
      Dim xRg As Range
      Dim xStr As String
      Dim xFd As FileDialog
      Dim xFileName As String
      Dim xFileNum As Long
      Dim RegExp As Object
      Dim xF As Object
      Dim xSF As Object
      Dim xFso As Object
      xFileName = Dir(xFdItem & "*.pdf", vbDirectory)
      xStr = ""
      Do While xFileName <> ""
      Cells(I, 1) = xFileName
      Set RegExp = CreateObject("VBscript.RegExp")
      RegExp.Global = True
      RegExp.Pattern = "/Type\s*/Page[^s]"
      xFileNum = FreeFile
      Open (xFdItem & xFileName) For Binary As #xFileNum
      xStr = Space(LOF(xFileNum))
      Get #xFileNum, , xStr
      Close #xFileNum
      Cells(I, 2) = RegExp.Execute(xStr).Count
      Cells(I, 3) = xFdItem & xFileName
      Cells(I, 4) = FileLen(xFdItem & xFileName)
      I = I + 1
      xFileName = Dir
      Loop
      Columns("A:B").AutoFit
      Set xFso = CreateObject("Scripting.FileSystemObject")
      Set xF = xFso.GetFolder(xFdItem)
      For Each xSF In xF.SubFolders
      Call SunTest(xSF.Path & "\", I)
      Next
      End Sub
      • To post as a guest, your comment is unpublished.
        Daphne · 1 years ago
        This is so great. Thanks!
  • To post as a guest, your comment is unpublished.
    Mat · 1 years ago
    Wov! so many thanks for sharing, this VBA code is a killer!! It works flawlessly with Excel O365
  • To post as a guest, your comment is unpublished.
    Prashant Narayankar · 1 years ago
    What if I want to run through subfolders too?
    • To post as a guest, your comment is unpublished.
      skyyang · 1 years ago
      Hello, Prashant,
      To get the number of all the PDF files from folder and subfolders, please apply the below code:

      Sub Test()
      Dim I As Long
      Dim xRg As Range
      Dim xStr As String
      Dim xFd As FileDialog
      Dim xFdItem As Variant
      Dim xFileName As String
      Dim xFileNum As Long
      Dim RegExp As Object
      Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
      If xFd.Show = -1 Then
      xFdItem = xFd.SelectedItems(1) & Application.PathSeparator
      Set xRg = Range("A1")
      Range("A:B").ClearContents
      Range("A1:B1").Font.Bold = True
      xRg = "File Name"
      xRg.Offset(0, 1) = "Pages"
      I = 2
      Call SunTest(xFdItem, I)
      End If
      End Sub

      Sub SunTest(xFdItem As Variant, I As Long)
      Dim xRg As Range
      Dim xStr As String
      Dim xFd As FileDialog
      Dim xFileName As String
      Dim xFileNum As Long
      Dim RegExp As Object
      Dim xF As Object
      Dim xSF As Object
      Dim xFso As Object
      xFileName = Dir(xFdItem & "*.pdf", vbDirectory)
      xStr = ""
      Do While xFileName <> ""
      Cells(I, 1) = xFileName
      Set RegExp = CreateObject("VBscript.RegExp")
      RegExp.Global = True
      RegExp.Pattern = "/Type\s*/Page[^s]"
      xFileNum = FreeFile
      Open (xFdItem & xFileName) For Binary As #xFileNum
      xStr = Space(LOF(xFileNum))
      Get #xFileNum, , xStr
      Close #xFileNum
      Cells(I, 2) = RegExp.Execute(xStr).Count
      I = I + 1
      xFileName = Dir
      Loop
      Columns("A:B").AutoFit
      Set xFso = CreateObject("Scripting.FileSystemObject")
      Set xF = xFso.GetFolder(xFdItem)
      For Each xSF In xF.SubFolders
      Call SunTest(xSF.Path & "\", I)
      Next
      End Sub

      Please try, hope it can help you!
      • To post as a guest, your comment is unpublished.
        ThomasB · 11 months ago
        Can you help me to also get the creator and dimensions of the file?
      • To post as a guest, your comment is unpublished.
        Aleca Tesseris Sulli · 1 years ago
        This is wonderful, thank you. I would like to run through subfolders too. Where/how in the above code do I add these additional commands? what would the whole thing look like?
      • To post as a guest, your comment is unpublished.
        Mat · 1 years ago
        Your subfolder code works fine! thanks
  • To post as a guest, your comment is unpublished.
    pedrohmc1@gmail.com · 2 years ago
    Regards

    There is a problem with the program, I am using version 2019 of Office, and the pages seem to be counting badly the first 9 accumulated pages I get zero, in the ninth accumulated page I get 10.

    Can you please help me with that inconvenience?

    Beforehand thank you very much.

    Atte.

    Pedro
    • To post as a guest, your comment is unpublished.
      Rob Haughey · 1 years ago
      The code is good structure for how to do this kind of thing but that regexp will give unreliable results for many pdfs. The regexp being searched for (/Type\s*/Page[^s]), will not work in SECURED pdfs (count will be zero). Also pdfs tools and versions vary in how they mark pages. It could be accurate if you know that all your pdfs are created using the same structure (version and tools).
      • To post as a guest, your comment is unpublished.
        Pedro Marza · 11 months ago
        Thank you very much for your answer, I solved the problem by saving the files as: "Optimized PDF"
        • To post as a guest, your comment is unpublished.
          Dave · 7 months ago
          100% agree with Pedro, I was having the same problem as Rob where some PDF page counts were wrong. But if you make sure that all files are saved as "Optimized PDF" in the folder it will get all the pages correct. This worked for me on over 100 separate PDF files. You can bulk optimize as well with Acrobat Pro. Overall great code, worked right out of the box if you will.
  • To post as a guest, your comment is unpublished.
    Suzie · 2 years ago
    HOLY! This is awesome! Thank you so much! I'm a printer and have been doing printit.txt and filling in by hand! This is going to make quoting and checking jobs SO MUCH EASIER! Thanks again!!!
  • To post as a guest, your comment is unpublished.
    Pedro · 2 years ago
    Saludos


    Hay algún problema con el programa, yo estoy usando la versión 2019 de Office, y las páginas parece que las va contando de mal las primeras 9 páginas acumuladas me sale cero, en la novena página acumulada me sale 10.

    ¿Por favor me puedes ayudar con ese inconveniente?

    De antemano muchas gracias.

    Atte.

    Pedro
  • To post as a guest, your comment is unpublished.
    Fawaz · 2 years ago
    Not working properly, for some pdfs, for some pdfs it shows 0 and for some incorrect page numbers
    • To post as a guest, your comment is unpublished.
      skyyang · 2 years ago
      Hi, Fawaz,
      The code works well in my Excel, which Excel version do you use?
      Or you can send your detailed problem or pdf files to my Email: skyyang@extendoffice.com.
      • To post as a guest, your comment is unpublished.
        JC · 2 years ago
        Hi skyyang,

        I've the same problem as Fawaz. I use MS Office Professional Plus 2013.

        Thanks for your help!

        Best regards
  • To post as a guest, your comment is unpublished.
    Chase C · 2 years ago
    Works great! Many thanks!
    • To post as a guest, your comment is unpublished.
      Merlin · 1 years ago
      Thank you very much for posting such informative message