我想从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文档。
发布于 2018-05-01 11:41:55
尝试:
Set doc = wordApp.Documents.Open(docPath)您正在获取的String是您创建的对象的一些属性;可能是Object.................insert MsgBox doc的Name来查看它是什么。
发布于 2018-05-01 12:03:56
虽然缺少的基本上是“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 = Nothinghttps://stackoverflow.com/questions/50115587
复制相似问题