【问题标题】:Macro using Documents.Open doesn't return a Document, but a String.使用 Documents.Open 的宏不返回文档,而是返回字符串。
【发布时间】:2018-05-01 11:20:13
【问题描述】:

我想从 Excel 宏中打开和读取 Word 文档的段落。这是让我感到困惑的示例代码:

Sub example()

    Dim docPath
    docPath = "C:\temp\test.docx"

    Dim wordApp
    Set wordApp = CreateObject("Word.Application")

    Dim doc
    doc = wordApp.Documents.Open(docPath)

    MsgBox (TypeName(doc)) 'This line displays String. According to the documentation it should be a Document.

End Sub

根据文档,Documents.Open 方法应该返回一个可以操作的 Document。但是当我检查它的类型时,它说它返回了一个字符串。显然我不能遍历字符串的段落:

https://msdn.microsoft.com/en-us/vba/word-vba/articles/documents-open-method-word

文档有错吗?难道我做错了什么?更重要的是,如何从 Excel 宏中循环遍历 Word 文档的段落?

如果这很重要,我正在使用 Office 365,并且我在 C:\temp\test.docx 创建了一个小型 Word 文档。

【问题讨论】:

  • 你缺少一个 Set
  • 哦。你是对的。为什么它返回一个没有 Set 的字符串,而是一个有 Set 的 Document?
  • ........见下文........

标签: excel vba


【解决方案1】:

尝试:

Set doc = wordApp.Documents.Open(docPath)

你得到的String 是你创建的对象的一些属性;可能是对象的Name........插入MsgBox doc 看看它是什么。

【讨论】:

【解决方案2】:

虽然基本上缺少的是“Set Doc = ...”,但你肯定会遇到这样的代码的麻烦。为防止出现一些建议和入门代码(您的代码确实有点修改):

从 Tools\References 添加 Word 对象引用并“键入”您的对象。键入它们将使编写具有智能感知支持的代码变得更加容易。 永远不要让对象这个词挂在那里。完成后摆脱它。

示例:

Dim docPath
docPath = "C:\temp\test.docx"

Dim wordApp As Word.Application
Set wordApp = CreateObject("Word.Application")

Dim doc As Word.Document
Set doc = wordApp.Documents.Open(docPath)

For i = 1 To doc.Paragraphs.Count
  Cells(i, 1) = doc.Paragraphs(i).Range.Words.Count
  Cells(i, 2) = doc.Paragraphs(i)
Next


wordApp.Quit

Set doc = Nothing
Set wordApp = Nothing

【讨论】:

  • 非常感谢。我会实现这个。我的 VBA(显然)有点生疏了。
猜你喜欢
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 2020-10-15
  • 2019-09-15
  • 2018-02-28
  • 1970-01-01
  • 2019-11-27
相关资源
最近更新 更多