How to work out if Word has closed

M

Mike NG

In relation to my thread yesterday "Waiting for a specific named
document to close" I have the following code

<standard automation>

On Error GoTo dun
Do Until lbDone
DoEvents
lbDone = True

With loWord
For liLoop = 1 To loWord.Documents.Count
If loWord.Documents(liLoop).Name = lsDocName Then
lbDone = False
Exit For
End If
Next
End With
Loop

dun:
Set loWord = Nothing


I need to know how the loop was exited - i.e. was it word closing, or
the document being closed. I could use another boolean which I set to
True and the same time as setting lbDone to False, but I'd like to just
know what the condition should be on loWord as I believe this should be
possible. I noticed from the debugger that whilst Word is active,
loWord has a value something like "Microsoft Word" and if it was closed
it will have a value of Nothing. Is this the right approach or should I
be testing something else


I have seen this kind of code for latching onto an already open Word
object which would also do the trick but I feel I should be able to put
something in my loop


On Error Resume Next
Set loWord = GetObject(, "Word.Application")
If Err Then
'No, word is not running
Err.Clear
End If
 
W

Word Heretic

G'day Mike NG <[email protected]>,

First, if you With, get rid of that of object as a prefix inside the
With, ie change:
With loWord
For liLoop = 1 To loWord.Documents.Count

to

With loWord
For liLoop = 1 To .Documents.Count

this will run much faster for you as well as reduce code size.


Next, your specific answer, I'd try something like this. It avoids
program errors and shows you how to tell if Word is valid or not. It
has a nice With usage to speed it along its way. It avoids
recalculating properties twice. Thus it is now compliant with my VBA
Beginner's Spellbook's checklist.

I typed the new vars for you.

'Declare
Dim DocCount as Long
Dim WordIsOpen as Boolean
Dim DocOpen as Boolean

'Init
DocOpen=True

'Main
Do Until Not DocOpen
DoEvents

WordIsOpen = not(loWord is Nothing)
if WordIsOpen then
with loWord.Documents
DocCount=.Count

If DocCount>0 then

For liLoop = 1 To DocCount
DocOpen=(.item(1).Name = lsDocName)
if DocOpen then exit for
next

Else 'No Dox!

DocOpen=False

end if 'documents
end with 'documents

else 'Word aint open
DocOpen=False
end if
Loop

'Terminate
If WordIsOpen then Set loWord = Nothing




Steve Hudson - Word Heretic
Want a hyperlinked index? S/W R&D? See WordHeretic.com

steve from wordheretic.com (Email replies require payment)


Mike NG reckoned:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top