Macro to Get Page Count of PDF Files

Macro to Get Page Count of PDF Files

April 11, 2017

SEE ON UPDATED ON THIS POST IN THE TIP OF THE NIGHT FOR APRIL 13, 2017.  

 

There's some VBA code posted on this site, 

https://www.mrexcel.com/forum/excel-questions/347911-visual-basic-applications-page-count.html  

which lets you generate a list in an Excel worksheet showing the page count of PDFs in a specified folder.

 

 

Press ALT + F11 from Excel in order to enter Visual Basic.   Right click on a Module and select Insert . . . Module .  Then paste the below code in.  [You may want to copy the code directly from the mrexcel.com, as the Wix text editor may alter the formatting of the code so it doesn't work.]

 

On the line beginning My Path = , enter the path to the directory containing the PDFs that you need page counts for. 

 

 

Press the play button and the macro will generate a list of the file names in column A and their page totals in column B.

 

 

 

Thanks to Haluk for posting this code!

 

 

Sub Test()
    Dim MyPath As String, MyFile As String
    Dim i As Long
    MyPath = "C:\TestFolder"
    MyFile = Dir(MyPath & Application.PathSeparator & "*.pdf", vbDirectory)
    Range("A:B").ClearContents
    Range("A1") = "File Name": Range("B1") = "Pages"
    Range("A1:B1").Font.Bold = True
    i = 1
    Do While MyFile <> ""
        i = i + 1
        Cells(i, 1) = MyFile
        Cells(i, 2) = GetPageNum(MyPath & Application.PathSeparator & MyFile)
        MyFile = Dir
    Loop
    Columns("A:B").AutoFit
    MsgBox "Total of " & i - 1 & " PDF files have been found" & vbCrLf _
           & " File names and corresponding count of pages have been written on " _
           & ActiveSheet.Name, vbInformation, "Report..."
End Sub
'
Function GetPageNum(PDF_File As String)
    'Haluk 19/10/2008
    Dim FileNum As Long
    Dim strRetVal As String
    Dim RegExp
    Set RegExp = CreateObject("VBscript.RegExp")
    RegExp.Global = True
    RegExp.Pattern = "/Type\s*/Page[^s]"
    FileNum = FreeFile
    Open PDF_File For Binary As #FileNum
        strRetVal = Space(LOF(FileNum))
        Get #FileNum, , strRetVal
    Close #FileNum
    GetPageNum = RegExp.Execute(strRetVal).Count
End Function

 

Please reload

Some elements on this page did not load. Refresh your site & try again.

Contact Me With Your Litigation Support Questions:

seankevinoshea@hotmail.com

  • Twitter Long Shadow

© 2015 by Sean O'Shea . Proudly created with Wix.com