How to create a Word document using current Word instance, then close it.

I have a project that creates a number of Word documents, one after the other. The first one document is to open Word and the remainder will use the same Word instance. After each document is created, it is to be printed then closed before another document is created.

How would I handle the Word application when creating the documents and then disposing of the document object without any 'save to normal.dot' dialogues?
TeDeSmAsked:
Who is Participating?
 
CodeCruiserCommented:
Try this

oWord = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application")

If IsNothing(oWord) Then
   oWord = New Word.Application
End If



This will get the reference to active object if one is open or open one if there is none open.
0
 
PandaPantsCommented:
You should be able to close each document with the parameter wdDoNotSave. If that gives you trouble, try setting the Saved property of the document to True, then closing it.
0
 
Joanne M. OrzechManager, Document Services CenterCommented:
You should just go into Word and tell it not to prompt you to save normal.dot.

Tools, Options, Save... uncheck "Prompt to save change to normal"
0
Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

 
CodeCruiserCommented:
>without any 'save to normal.dot' dialogues?

Is that all you need help with?
0
 
TeDeSmAuthor Commented:
The option to not save to normal.dotm is unchecked.

However, I think the problem I had is with the code that creates the documents. I have amended it to include a Try/Catch as below. However I have made an assumption that the only exception thrown would be if Word was already open. In VBA a specific error 429 would be thrown.


Try
  oWord = GetObject(, "Word.Application")
Catch ex As Exception
' Word is not already open, create new Word object
  oWord = CreateObject("Word.Application")
  Err.Clear()
End Try

Open in new window

0
 
TeDeSmAuthor Commented:
Still had to use Try/Catch to handle when Word was not open, however it does give an exception code.
Try
oWord = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application")
Catch
oWord = New Word.Application
End Try
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.