Reputation: 444
I want to know whether WINWORD.EXE
is running when I open a Word document embedded in Excel. If it is not already running then I want to use objWord.Quit
. It's possible the user is working in Word and I don't want to interfere with that, so in that case objWord.Quit should not be executed.
I have this -sniped- code:
'Variable declaration
Dim objWord As Word.Application
Dim objDoc As Word.Document
objWord
is being instantiated like this:
ActiveSheet.OLEObjects(P).Activate
Set objWord = GetObject(, "Word.Application")
At end of the procedure:
Set objDoc = Nothing
Set objWord = Nothing
But the WINWORD.EXE
instance remains running.
How can I determine whether WINWORD.EXE
Is running when the procedure begins?
Upvotes: 1
Views: 459
Reputation: 444
Using Word.Documents.Count
:
Function IsWinwordRunning() As Boolean
Dim DCount As Integer
Dim IsWinwordRunning As Boolean
IsWinwordRunning = False
On Error Resume Next
DCount = Word.Documents.Count
If Err = 429 Then DCount = 0
If DCount > 0 Then IsWinwordRunning = True
End Function
Upvotes: 0
Reputation: 25663
To have an instance of Word that you can be sure the user is not working in, use the New
keyword. Unlike GetObject this will force a new instance to start. Then you can use objWord.Quit.
Set objWord = New Word.Application
However: Rather than starting an instance of Word, or using an existing instance, it seems from your problem description it would make more sense to work with the embedded document object, directly. Here's some sample code:
Sub Test()
Dim ws As Excel.Worksheet
Dim currCel As Excel.Range
Dim oDoc As OLEObject
'to restore the current selection after activating the Word document
Set currCel = Application.Selection
Set ws = ActiveWorkbook.Worksheets("Sheet1")
'Note: I named the embedded document, using code
'If you don't want to do that, you need the index value
'as you have in your code: OLEObjects(P)
Set oDoc = ws.OLEObjects("WordDoc")
WorkWithWordDoc oDoc, currCel
Set oDoc = Nothing
End Sub
Sub WorkWithWordDoc(oDoc As OLEObject, selRange As Excel.Range)
Dim doc As Word.Document
Dim wasActivated As Boolean
Dim cc As Word.ContentControl
'On first opening the Workbook
'the OLE interface of the OLEObject
'isn't accessible, so you need to activate
'it if the error occurs
wasActivated = True
On Error Resume Next
Set doc = oDoc.Object
If Err.Number = 1004 Then
Excel.Application.ScreenUpdating = False
oDoc.Activate
wasActivated = False
Set doc = oDoc.Object
Excel.Application.ScreenUpdating = True
End If
On Error GoTo 0
'Code to work with the document comes here
'Clean up
If Not wasActivated Then
'Deactivate the document
selRange.Select
End If
Set doc = Nothing
End Sub
Upvotes: 1