将数据从pdf传输到Excel

时间:2018-02-01 19:32:26

标签: excel excel-vba pdf vba

我有一个工作代码将数据从pdf传输到S / S,但有一个问题。我希望代码继续通过pdf页面并在结束时停止。问题在于如何让进程识别正在pdf中显示的页面:

  Sub Trial()

Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim lastrow4 As Long
Dim ws As Worksheet
Dim displaypage As Integer

   pathAndFileName = "C:\New Folder\2002.pdf"
   adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat DC\Acrobat\Acrobat.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("00:00:2")
    SendKeys "^a"
    SendKeys "^c"
    ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(1)
        Range("A1").Select
        ws.Paste
   Application.CutCopyMode = False
    Application.Wait Now + TimeValue("00:00:1")
    SendKeys "^{PGDN}"


  'the problem starts here  there is no recognition of the display page number and it moves to the else part

  If displaypage = 2 Then
    SendKeys "^a"
    SendKeys "^c"
    Application.Wait Now + TimeValue("00:00:1")
    ThisWorkbook.Activate
    lastrow4 = Sheets("Sheet1").Range("A65536").End(xlUp).Row
    Range("A" & lastrow4 + 1).Select
    ws.Paste
  Else
    SendKeys "^q"
    End If

如果我省略“dispalaageage”if / then sequence并使用一定数量的pdf页面,但是我希望它是开放的,所以我可以为任何大小的文档格式化它并在它完成时停止它所有页面。我不需要直到或循环部分,我只需要知道如何设置事物以识别pdf所在的页面,以便它将正确地通过If序列。 谢谢, E.T.

1 个答案:

答案 0 :(得分:0)

我能够根据我的需要调整此代码。也许其他人也可以使用它。

Sub Test() Dim MyPath As String, MyFile As String Dim i As Long MyPath = "C:\New Folder" 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