Opening an MS Word doc from Excel file.


Posted by Michele on May 31, 2001 11:49 PM

To open an MS Word file from and Excel Workbook, I use the following VB code (thanks to guidance from Ivan Moala). This works but the problem is that it opens a new copy of MS Word everytime it gets executed and it also opens the file requested even if that file is already opened.

Static WordObj
Set WordObj = Nothing
Set WordObj = CreateObject("Word.Application")
On Error GoTo FileErr
WordObj.Documents.Open (FileNm)
On Error GoTo GenErr
WordObj.Visible = True

So to solve my problem, does anyone know how to do the following:

If desired MS Word file is already opened, then
Activate MS Word & file.
Goto EOJ
ElseIf MS Word is already opened, then
Open desired MS Word file but not a new MS Word.
Goto EOJ
Else Goto execute my above code which opens MS Word
and the desired MS Word file.
Goto EOJ
End If

Many thanks,
Michele



Posted by Dax on June 01, 2001 4:08 AM


Hello Michele,

This code attempts to activate Word by using GetObject. If this fails then it creates a new Word application. It then attempts to activate the FileNm document and if this fails then opens it.

HTH,
Dax.

Sub OpenWordDoc()
Dim WordObj As Object, FileNm As String
Dim Doc As Object

Err.Clear

On Error Resume Next
Set WordObj = GetObject(, "Word.Application")

If Err.Number = 429 Then
Set WordObj = CreateObject("Word.Application")
End If

FileNm = "c:\testdoc.doc"

WordObj.Visible = True
WordObj.Activate
Set Doc = WordObj.Documents(FileNm)

If Doc Is Nothing Then
Set Doc = WordObj.Documents.Open(FileNm)
End If

On Error GoTo 0

End Sub