PDA

View Full Version : GetObject to open Word File



Giri
06-15-2011, 03:18 AM
Hi Guys,

I have been trying to use VBA to open up a Word document. I wrote some code to do this while also checking to see whether Word was already open but I the result is that the code is continuously jumping to the MsgBox line...

Any help would be greatly appreciated!!



Option Explicit


Public Sub Giri()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim FileName As String
Dim myObject As Object

FileName = "C:\Users\Giridhaar\Desktop\Links.docx"

On Error Resume Next

Set myObject = GetObject(, "Word.Application")

If myObject Is Nothing Then

Set wrdApp = CreateObject("Word.Application")

wrdApp.Documents.Open FileName

Else

For Each wrdDoc In wrdApp

If StrComp(wrdDoc.FullName, FileName, vbTextCompare) = 0 Then

MsgBox "File already Open!"


Else

wrdApp.Documents.Open FileName


End If

Next wrdDoc

End If

End Sub

mancubus
06-15-2011, 05:21 AM
try


'http://www.mrexcel.com/archive/Office/19023.html

On Error Resume Next

Set wrdApp = GetObject(, "Word.Application")

If Err.Number <> 0 Then 'Word isn't already running
Set wrdApp = CreateObject("Word.Application")
End If

On Error GoTo 0

Set wrdDoc = wrdApp.Documents.Open(FileName)

wrdApp.Visible = True

mancubus
06-15-2011, 05:25 AM
ps: reference to "Microsoft Word 14.0 (or 12.0) Object Library" must be set.

Kenneth Hobs
06-15-2011, 05:39 AM
The problem is that you did not reset the error to nothing after setting the application object. Another problem is that you did not set the objects to nothing. As it is, a hidden instance could be left at the end.

Here is an example:
'http://www.mrexcel.com/forum/showthread.php?t=333200
Sub FillForm()
Dim wdApp As Object, WD As Object, rn As Long
rn = ActiveCell.Row
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0

Set WD = wdApp.Documents.Open(ThisWorkbook.Path & "\Car Information Page.doc")

wdApp.Visible = True
With WD
.FormFields("Brand").Result = Cells(rn, "B")
.FormFields("Model").Result = Cells(rn, "C")
.FormFields("Chasis").Result = Cells(rn, "D")
.FormFields("Engine").Result = Cells(rn, "E")
.FormFields("Color").Result = Cells(rn, "F")
.FormFields("YearMonth").Result = Cells(rn, "G").Value & "/" & Cells(rn, "H").Value
End With

Set WD = Nothing
Set wdApp = Nothing
End Sub

Giri
06-21-2011, 03:43 AM
Thanks so much for the replies.

I have managed to get it working ;)

Kind Regards,

Giri