【问题标题】:How to open a PDF?如何打开PDF?
【发布时间】:2020-10-16 14:58:34
【问题描述】:

我正在尝试在 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 文档打开。

【问题讨论】:

  • 您是在 Word 还是 Excel 中运行此代码?
  • 您好,我目前正在 Word 中运行此代码,但我想如果添加正确的引用,我可以在 Excel 中运行它。
  • “PDF 文件”不是 Open 的 Format 参数的有效参数。我搜索了 WdOpenFormat 枚举 并得到了这个页面:docs.microsoft.com/en-us/office/vba/api/word.wdopenformat
  • 好收获。我可以打开文档了,谢谢
  • 这适用于 Excel,但总体思路应保持不变 here。我个人会尽量避免发送密钥解决方案并使用 api。

标签: vba ms-word


【解决方案1】:

看起来您有一些为 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 将尝试转换它

【讨论】:

  • 有些 pdf 文件不能在 Word 中编辑。它们只是文字图片,需要通过 OCR 程序运行。