I've got an (legacy VB.Net) application that pulls data from some tables, populates a word template, and concatenates that template with several other files.
On several machines this works with no issues, but for one client there is a persistent problem where the Word Interop code throws Object reference not set to an instance of an object
when attempting to open the template file (which exists, and has no permission issues, etc).
Dim doc As Document
Dim msWord As Microsoft.Office.Interop.Word.Application
msWord = New Microsoft.Office.Interop.Word.Application
' next line throws "Object reference not set to an instance of an object"
doc = msWord.Documents.Add(verifiedTemplateName)
When operating in a (horribly implemented) debug mode that throws up a bunch of modal dialogs that starts-n-stops execution, the exception is not thrown.
Dim doc As Document
Dim msWord As Microsoft.Office.Interop.Word.Application
msWord = New Microsoft.Office.Interop.Word.Application
MsgBox("VooDoo coder at work")
' now no exception is thrown
doc = msWord.Documents.Add(verifiedTemplateName)
When operation in normal mode, with a delay of some seconds, the exception is not thrown.
Dim doc As Document
Dim msWord As Microsoft.Office.Interop.Word.Application
msWord = New Microsoft.Office.Interop.Word.Application
Delay(5) ' function that pauses for one second
' now no exception is thrown
doc = msWord.Documents.Add(verifiedTemplateName)
This suggests that, on some machines, the Word.Application takes some time to "spin up."
But how best to trap for this, and continue once it exists; or throw an error if the time-frame is obscene (as always, best decided by the local jurisdiction)?
This is also an issue reported by others in the MSDN forums @ WordApplication.Documents.Add Method return null?
The only suggested solutions I've seen are potential infinite loops:
Document nulldoc = null;
do
{
document = application.Documents.Add(template, newtemplate, documenttype, visible);
Thread.Sleep(100);
}
while (document == nulldoc);
Is there a better solution to this than dumb delays, or possibly-infinite check-loops?
See Also: Error when creating an instance of Word in VB.net. Same error, similar code; but the solution was to ensure that the target file existed (which does, in my case).