Home » excel » excel – Macro using Documents.Open doesn't return a Document, but a String.

excel – Macro using Documents.Open doesn't return a Document, but a String.

Posted by: admin May 14, 2020 Leave a comment

Questions:

I want to open and read paragraphs of a Word document from an Excel macro. Here’s the sample code that confuses me:

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

According to the documentation the Documents.Open method should return a Document that you can operate on. But when I check the type it says it has returned a String. Obviously I can’t loop through the paragraphs of a string:

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

Is the documentation wrong? Am I doing something wrong? More importantly, how do I loop through the paragraphs of a Word document from an Excel macro?

I’m using Office 365 if that matters and I have created a small Word document at C:\temp\test.docx.

How to&Answers:

try:

Set doc = wordApp.Documents.Open(docPath)

The String you are getting is some property of the Object you have created; might be the Name of the Object……………..insert MsgBox doc to see what it is.

Answer:

Although basically what is missing is a ‘Set Doc = …’ you are guaranteed to get into trouble with a code like that. To prevent that some suggestions and a starter code (your code really, a little bit modified):

Add Word object reference from Tools\References and “type” your objects. Typing them would make it much easier to write code with intellisense support.
Never ever let the word object hang out there. Get rid of it when you are done.

Sample:

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