Note: The other languages of the website are Google-translated. Back to English
로그인  \/ 
x
or
x
REGISTER  \/ 
x

or

Excel에서 PDF 파일의 페이지 번호를 계산하는 방법은 무엇입니까?

특정 폴더에 여러 개의 Pdf 파일이있는 경우 이제 이러한 모든 파일 이름을 워크 시트에 표시하고 각 파일의 페이지 번호를 가져 오려고합니다. Excel에서이 작업을 어떻게 빠르고 쉽게 처리 할 수 ​​있습니까?

VBA 코드로 워크 시트의 폴더에서 Pdf 파일의 페이지 번호 계산


VBA 코드로 워크 시트의 폴더에서 Pdf 파일의 페이지 번호 계산

다음 VBA 코드는 모든 PDF 파일 이름과 각 페이지 번호를 워크 시트에 표시하는 데 도움이 될 수 있습니다. 다음과 같이하십시오.

1. PDF 파일과 페이지 번호를 가져올 워크 시트를 엽니 다.

2. 누르고 ALT + F11 키가 열립니다. 응용 프로그램 용 Microsoft Visual Basic 창.

3. 딸깍 하는 소리 끼워 넣다 > 모듈을 클릭하고 다음 매크로를 모듈 창문.

VBA 코드 : 워크 시트의 모든 PDF 파일 이름과 페이지 번호를 나열합니다.

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. 코드를 붙여 넣은 후 F5 이 코드를 실행하는 키와 검색 창이 튀어 나오면 나열하려는 Pdf 파일이 포함 된 폴더를 선택하고 페이지 번호를 계산하십시오. 스크린 샷을 참조하십시오.

문서 수 pdf 페이지 1

5. 그런 다음 OK 버튼을 클릭하면 모든 Pdf 파일 이름과 페이지 번호가 현재 워크 시트에 나열됩니다. 스크린 샷을 참조하십시오.

문서 수 pdf 페이지 2


최고의 사무 생산성 도구

Excel 용 Kutools는 대부분의 문제를 해결하고 생산성을 80 % 향상시킵니다.

  • 재사용: 빠르게 삽입 복잡한 공식, 차트 그리고 이전에 사용한 모든 것; 셀 암호화 암호로; 메일 링리스트 생성 이메일 보내기 ...
  • 슈퍼 포뮬러 바 (여러 줄의 텍스트와 수식을 쉽게 편집 할 수 있습니다.) 레이아웃 읽기 (많은 수의 셀을 쉽게 읽고 편집합니다.) 필터링 된 범위에 붙여 넣기...
  • 셀 / 행 / 열 병합 데이터 손실없이; 셀 내용 분할; 중복 행 / 열 결합... 중복 셀 방지; 범위 비교...
  • 중복 또는 고유 선택 행; 빈 행 선택 (모든 셀이 비어 있음); 슈퍼 찾기 및 퍼지 찾기 많은 통합 문서에서; 무작위 선택 ...
  • 정확한 사본 수식 참조를 변경하지 않고 여러 셀; 참조 자동 생성 여러 시트에; 글 머리 기호 삽입, 확인란 등 ...
  • 텍스트 추출, 텍스트 추가, 위치 별 제거, 공간 제거; 페이징 부분합을 만들고 인쇄합니다. 셀 내용과 주석 간 변환...
  • 슈퍼 필터 (다른 시트에 필터 구성표 저장 및 적용) 고급 정렬 월 / 주 / 일, 빈도 등 특수 필터 굵은 기울임 꼴로 ...
  • 통합 문서와 워크 시트 결합; 키 열을 기반으로 테이블 병합; 데이터를 여러 시트로 분할; xls, xlsx 및 PDF 일괄 변환...
  • 300 개 이상의 강력한 기능. Office / Excel 2007-2019 및 365를 지원합니다. 모든 언어를 지원합니다. 기업 또는 조직에 쉽게 배포 할 수 있습니다. 전체 기능 30 일 무료 평가판. 60 일 환불 보장.
kte 탭 201905

Office Tab은 Office에 탭 인터페이스를 제공하여 작업을 훨씬 쉽게 만듭니다.

  • Word, Excel, PowerPoint에서 탭 편집 및 읽기 사용, Publisher, Access, Visio 및 Project.
  • 새 창이 아닌 동일한 창의 새 탭에서 여러 문서를 열고 만듭니다.
  • 생산성을 50 % 향상시키고 매일 수백 번의 마우스 클릭을 줄입니다!
officetab 하단
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