Reputation: 1165
I'm having an issue with this bit of code, and I'm not quite sure what the problem is to be honest. The original problem was that the application I've written opens an instance of word, but if there is already an instance of word on the machine, it just opens a second instance, but it doesn't insert the document I create inside that instance. What I end up with is two windows, one if Word itself, no document, and one that's Word and the document. Their original running word application is still running as normal, in its own Word/Document combination, as it should have. I tried to get around this issue by grabbing the running instance of Word via getObject, but it simply keeps returning a failure.
I read that you have to give word focus and then lose focus for it to get listed with the ROT, but even after waiting 10 minutes, it still returns the following error:
AnswerWizard = {"Error HRESULT E_FAIL has been returned from a call to a COM component."}
I was wondering if there was something I'm missing about getObject and the ability to link into another instance of an Office application that's causing this error?
Information:
Windows 7
Word 2003
Desktop VB Application
Code:
Private wordApp As Word.Application
Public Sub New()
Try
wordApp = CType(GetObject(, "Word.Application"), Word.Application)
Catch ex As Exception
wordApp = New Word.Application
End Try
End Sub
Note: Tried with, and without CType, didn't matter. It does work if there are NO instances of word running, but that's only because it goes to my exception.
Problem:
If I try to link into an already running instance of Word, the code runs through without throwing an error, but I get AnswerWizard = {"Error HRESULT E_FAIL has been returned from a call to a COM component."}. My code then continues to open an instance of blank word, and word/document, a total of two windows when there should only be one. Am I missing something about getObject?
Upvotes: 0
Views: 1006
Reputation: 2762
In GetObject and CreateObject behavior of Office automation servers, Microsoft recommends avoiding GetObject(). I agree with this: unless you need to interact with a document in the user's session, opening a second document risks interference from the user. An independent instance can just get on with its work invisibly, or with the user interface locked.
Your problems when another instance of Word is running are familiar to me, albeit in a VBA environment.
Many keywords which look like objects in the Office application documentation are, in fact, methods of the Application object - one of the most common in Word is Selection
. It's vital to specify your application object with these methods: wordApp.Selection
, otherwise the method is applied to the first instance of Word which is running, usually resulting in an error.
Upvotes: 1