Trying to close all open documents except one

C

CPutnam

Hi, all. I've created a macro that merges a few documents and then combines
some of the text from one into another and saves that as a new document with
a new name. Then I want to close all the documents except the new one.
Here's the code that I'm using:

For Each Document In Documents
If Document.Name <> "c:\download\ProjAbstractMergeFiles\" &
strDocName & ".doc" Then
Document.Activate
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
End If
Next Document

(Where "c:\download\ProjAbstractMergeFiles\" & strDocName & ".doc" is the
name of the new document (the user supplied strDocName). Referring to the
document this way works when creating the document and when activating it.)

However, the result of this code is that all open documents are closed!
When I step through my macro code, it looks like it's going through the code
correctly and NOT activating the document I want to keep open but then POOF!
it's closed.

(I'm using Word97 to do this macro but that newsgroup didn't look active at
all. Don't know if this matters but I have attached the macro directly to
the document because I need to distribute the document to a lot of users,
some of whom will be using Word 2002.)

Thanks in advance for any ideas you can give to me. Carol.
 
M

Malcolm Smith

Carol

When you create a document it's best to get a pointer to it. For example,
if create a document thus:

Dim oNewDocument as Document

set oNewDocument = Documents.Add

then you could refer to it always.


So if you had a loop such as:

dim oDocument as Document

for each odocument in documents
if oDocument <> oNewDocument then
oDocument.Close wddonotsavechanges
end if
next oDocument


Or something like this ought to do the trick. Again, apologies if this
doesn't compile as it's done from the top of my head.

- Malc
www.dragondrop.com
 
J

Jezebel

Good suggestion, but slightly risky coding. This line

if oDocument <> oNewDocument then

is not comparing the documents, but their default properties. In the case of
documents, this is the Name property. So in practice your code will usually
work; but since the name does not include the path it would fail if you had
two documents with the same name, but saved in different folders. The method
will fail in general on objects that don't have default properties.

When comparing objects you should use 'is' instead --

if not oDocument is oNewDocument then ...
 
M

Malcolm Smith

if not oDocument is oNewDocument then ...

You are entirely correct. I did give the caveat; and you did pick up the
point that I was comparing pointers. I have to apologise for this; I was
messing about with another language and the syntax got to me.

- Malc
 
Top