如何打开PDF?

How to open a PDF?

我正尝试在 Word 中使用 VBA 打开 PDF 文档,并最终进行一些文本操作。

我将下面的代码作为测试,它没有错误并且似乎正在打开 pdf。

当我尝试插入刚刚在 Word 中打开的 pdf 文本时,它会粘贴一个带有问号的框。我不确定我是否没有正确打开 PDF,或者文件是否正在打开。

'Earlier code truncated for brevity
Dim FSOSubFolder As Object
Dim FSOFile As Object
Dim anotherString As String

For Each FSOSubFolder In FSOFolder.SubFolders
    LoopAllSubFolders FSOSubFolder
Next

For Each FSOFile In FSOFolder.Files
    
    ActiveDocument.Range.InsertAfter ("File Name: " & FSOFile.Name & vbNewLine) 'This part works
    Dim myWord As Word.Application, myDoc As Word.Document
    Set myWord = New Word.Application  
    Set myDoc = myWord.Documents.Open(FileName:=FSOFile.Path, ConfirmConversions:=False, Format:="PDF Files")
    myDoc.Activate
    Selection.WholeStory
    anotherString = Selection.Range.Text
    myDoc.Close
    ActiveDocument.Range.InsertAfter (anotherString) 'This pastes a box with a question mark inside

    Set FSOFile = Nothing
    Set FSOSubFolder = Nothing

Next 

我没有抑制屏幕更新或警告,也没有看到打开新的 Word 文档。

您似乎为 Excel 编写了一些代码,并试图在 Word

中使用
    Dim myWord As Word.Application, myDoc As Word.Document
    Set myWord = New Word.Application  
    Set myDoc = myWord.Documents.Open(FileName:=FSOFile.Path, ConfirmConversions:=False, Format:="PDF Files")
    myDoc.Activate

因为你是 运行Word 中的代码,你已经有一个 Word 实例,所以没有必要打开一个新的,你肯定不想为创建一个新的 Word 实例您尝试打开的每个文件,尤其是当您的代码没有退出任何这些额外实例时。您没有看到正在打开的文档,因为您的代码没有使 Word 的其他实例可见。

您的代码已删除所有不必要的位:

   'Earlier code truncated for brevity
   Dim FSOSubFolder As Object
   Dim FSOFile As Object
   Dim anotherString As String

   For Each FSOSubFolder In FSOFolder.SubFolders
      LoopAllSubFolders FSOSubFolder
   Next
   
   Dim originalDoc As Word.Document
   Set originalDoc = ActiveDocument

   For Each FSOFile In FSOFolder.Files
    
      originalDoc.Range.InsertAfter ("File Name: " & FSOFile.Name & vbNewLine) 'This part works
      Dim pdfDoc As Word.Document
      Set pdfDoc = Documents.Open(filename:=FSOFile.Path, ConfirmConversions:=False, Format:=wdOpenFormatAuto)
      'use this if you just want the text content without formatting
      originalDoc.Range.InsertAfter pdfDoc.Content.Text
      'use this is if you want the formatted content
      'originalDoc.Range.InsertParagraphAfter
      'originalDoc.Paragraphs.Last.Range.FormattedText = pdfDoc.Content.FormattedText
      pdfDoc.Close

      Set FSOFile = Nothing
      Set FSOSubFolder = Nothing
   Next

当您尝试打开 pdf 文件时,您可能会收到通知,指出尽管设置了 ConfirmConversions:=False

,Word 仍会尝试转换它