Monday, July 02, 2007

Selection.Find crash

you wrote an application that works with Word object?
the application crashes in the middle of the run, after the debug you find that it crashes on this line:
WordObj.Selection.Find

well, it's not your fault, it's a microsoft bug. now, how you resolve it??
it's a tricky way,
what you should do is late binding
u should dim your word object as an General object and create it manualy, not by "new word"
here is a usefull code:
...


Dim wrdDoc As Object ' setting the word object as a general object
Dim IsWordRunning As Boolean

IsWordRunning = ApplicationIsRunning("Word.Application")
If IsWordRunning = True Then ' do
Set wrdApp = GetObject(, "Word.Application")
Else
Set wrdApp = CreateObject("Word.Application")
End If
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open(filename)


...


and here is the applicationisrunning function:

Function ApplicationIsRunning(ApplicationClassName As String) As Boolean
' returns True if the application is running
' example: If Not ApplicationIsRunning("Outlook.Application") Then Exit Sub
Dim AnyApp As Object
On Error Resume Next
Set AnyApp = GetObject(, ApplicationClassName)
ApplicationIsRunning = Not AnyApp Is Nothing
Set AnyApp = Nothing
On Error GoTo 0
End Function

No comments: