我想从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方法应该返回一个可以操作的文档。但当我检查它所说的类型时,它已经返回了一个字符串。显然,我无法遍历字符串的段落:
https://msdn.microsoft.com/en-us/vba/word-vba/articles/documents-open-method-word
文档错了吗?难道我做错了什么?更重要的是,如何从Excel宏循环浏览Word文档的段落?
我使用Office 365,如果这很重要,我在C:\ temp \ test.docx创建了一个小的Word文档。
答案 0 :(得分:1)
尝试:
(
您获得的(E_N_minus_1
是您创建的对象的某些属性;可能是对象的(E_N
.................插入E)))
以查看它是什么。
答案 1 :(得分:1)
虽然基本上缺少的是“Set Doc = ...”,但您可以确保使用类似的代码遇到麻烦。为了防止一些建议和入门代码(你的代码确实有点修改):
从Tools \ References添加Word对象引用并“键入”您的对象。键入它们会使用intellisense支持编写代码变得更容易。 永远不要让对象挂在那里。完成后摆脱它。
样品:
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