PDA

View Full Version : Documents.Count returns 0 with documents still open



the Core
10-20-2021, 10:09 PM
Dearest helpers,

I made a script in my normal.dotm file that should loop through all opened docs, executes some code on each, closes it and when the last one is closed it quits the grey window that's left over.

In code :

Do while Word.Application.Documents.Count <> 0

Documents(1).Activate
Call mycode()
Active Document.close()
Loop
Application.quit

It does do this, but it leaves documents open. I Guess I'm running multiple instances. How to actually loop all open documents?


Cor

arnelgp
10-21-2021, 01:14 AM
your doc where you are running this code is not exempted.
you need to Check If the Doc.Name is same as the Current document name
and prevent it from closing.

btw you will never get .Count of 0 because of same reason above.

the Core
10-21-2021, 03:39 AM
Well it kinda does all the time and that's the issue. Sorry for posting it in the CODE format.
Note that the VBA code runs from a normal.dotm template, not the Word document I'm editing.

I think new Word documents are opened in a new instance that isn't included in:

Word.Application.Documents.Count

When I have 3 Word files open the document count is 1. After closing that file the count is 0 and a completely grey window is left. That's closed with

Application.Quit

the Core
10-21-2021, 01:20 PM
Hi,

I've honestly been looking for an answer for months. Help is appreciated.

When I select 3 Word files and hit [enter], they are opened in 3 separate processes. How to count them all?

The following code doesn't work because it always returns 1 as each instance/process contains 1 of the documents.

Word.Application.Documents.Count

Actually I want to run a function on every opened document (like SaveAs PDF) and close them afterwards, one by one. Maybe I need to loop through every Word.Application?

Is that possible?

Cor

Chas Kenyon
10-21-2021, 06:39 PM
Yes, you are opening multiple instances of Word this way. If you have Word open (even with no document open) and then do the same thing, all three should open in the same instance.

the Core
10-21-2021, 09:06 PM
Thanks! Good to know it's default behaviour.
Now, how do I switch to another instance?

This does not seem to do the trick:

Dim wd As Object
Set wd = GetObject(, "Word.Application")
wd.Documents(1).Close

arnelgp
10-21-2021, 09:27 PM
it will always create new instance unlike other office apps.
https://support.microsoft.com/en-us/topic/a-new-instance-of-word-appears-to-run-when-you-create-or-open-an-additional-document-in-word-2000-and-in-later-versions-of-word-d7392d8e-1afc-8c4c-5e53-7f60b30ff49d

the Core
10-23-2021, 12:46 AM
Ok, but how to address it with VBA?

This is obviously not the answer:

Word.Application(2).Documents(1)

???