Sara Menoncin
Sara Menoncin

Reputation: 93

Modify an opened word document through Excel

How can I modify an opened word document through Excel with VBA? Here a bit of code I'm writing, but there's something wrong I can't understand.

Dim WordDoc As Word.Document
Dim WordApp As Word.Application
'ThisWorkbook is the opened Excel Workbook through which I control Word documents.

If Len(Dir(ThisWorkbook.path & "\Report.docx")) <> 0 then 
         'if the document exists in the folder where ThisWorkbook is saved, I check
         'if the document is already opened.

   If IsFileOpened(ThisWorkbook.path & "\Report.docx") 
         'if during the run-time I get here, it means that the document exists and 
         'it's already opened.
         'Now I want to get the reference to the opened document "Report.docx",
         'so I do a thing like this.

         Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")

         'When it tries to excute the instruction over, it gives me a message in which
         'it is written that the name is bad or inexistent, even if the document
         'is already opened. Is the instruction correct?

         Set WordApp= WordDoc.Application
         '...other code

   Else
         'if the document isn't opened, I open it.
      Set WordApp = CreateObject("Word.Application")
      Set WordDoc = WordApp.Documents.Open(ThisWorkbook.path & "\Report.docx") 
         '..other code
   End If

Else     'I create a new document called "Report.docx" if it doesn't exist 
         'in the folder where ThisWorkbook is saved.
   Set WordApp = CreateObject("Word.Application")
   Set WordDoc = WordApp.Documents.Add("Report.docx")
   '.... other code 
End If

Thanks in advance...

Upvotes: 0

Views: 2552

Answers (2)

Sara Menoncin
Sara Menoncin

Reputation: 93

I tried this version

path = ThisWorkbook.path & "\Report.docx"
Set WordApp = GetObject(path).Application

in place of

Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")

and it works.

Upvotes: 0

asp8811
asp8811

Reputation: 803

I tried this with an excel workbook and it worked

 Set WordDoc= Word.Application.Documents(ThisWorkbook.path & "\Report.docx")

should be

 Set WordDoc= Word.Documents("Report")

When I tried using the file path, I got Run-time error "9" Subscript out of range. When I used just the file name, it was successful.

Edit: After trying this with a word document, you do not need the application object and should not use the file extension. I can confirm that this works.

Upvotes: 0

Related Questions