Document( ).Activate

G

Greg

I have an open document. I then use VBA to open a second document

Sub Test()

Dim SecondDocument As Document

Set SecondDocument = Documents.Open(FileName:="C:\Word List.doc")

'Why do I have to use (2) below to activate the first document? I
seems like the original opened document would be (1).
Documents(2).Activate

End Sub
 
A

Alex Ivanov

When you open the SecondDocument it becomes ActiveDocument, which always has
index of 1.
Documents collection is ordered in a way that topmost open document has the
lowest index (1), second in a stack (2) and so forth.

You can't reasonably depend on the document index as it will change when you
activate another document.
 
J

Jay Freedman

I have an open document. I then use VBA to open a second document

Sub Test()

Dim SecondDocument As Document

Set SecondDocument = Documents.Open(FileName:="C:\Word List.doc")

'Why do I have to use (2) below to activate the first document? I
seems like the original opened document would be (1).
Documents(2).Activate

End Sub

Hi Greg,

Don't use Documents() at all! That's the point of assigning documents
to Document variables -- do this instead:

Sub Test()

Dim FirstDocument As Document, SecondDocument As Document

Set FirstDocument = ActiveDocument
Set SecondDocument = Documents.Open(FileName:="C:\Word List.doc")

FirstDocument.Activate

End Sub

Even better, use the properties of the two Document variables to do
your manipulations, and avoid activating any documents at all. The
classic situation is copying or cutting some piece of text in the
first doc and pasting it into the second doc. Instead, once you set up
Range objects in the two documents (usually by Find in the first doc,
and collapsing to the end of the second doc), all you need is

DestRange.FormattedText = SourceRange.FormattedText

No activation needed! Bonus, if the user has anything on the
clipboard, you don't disturb it.

BTW, I don't have an answer to the original question, why the indexes
in the Documents collection aren't in the expected order. <shrug>
 

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