Question

I'm not very used to VBA language, so I come to you for help to solve my problem.

Basically, what I want to do is, while having a MS Word 2010 document opened, open a new one, set the focus on it and do stuff with it.

The problem I'm facing is that I can effectively open the new document, but the .activate function to set the function on it doesn't work, as the instructions following it are still executed in the first document.

Here is my code:

Private Sub BOK_Click()

*...instructions...*

'Opens a new document
Application.Documents.Add

'Select the latest opened document and sets the focus on it
Application.Documents(Application.Documents.Count).Activate

* do stuff *

End Sub

If it may help, the full context is : I have a main template with 6 pre-filled templates in it, and following the choice of the user (from a drop-down form) it selects the right pre-filled template and opens it in a new Word document, then closed the main template.

Was it helpful?

Solution

What Documents.Add does:

  • Create a window
  • Render a copy of the provided (or Normal, in this case) template
  • Display it in the window
  • Raise the index of all open documents by 1
  • Assign index 1 to the newly added document
  • Bring the window to the front and give focus to it

There's (usually) no need to explicitly activate a document you just added. If you must or want to use Activate, it's best practice to reference a document by it's name, since indexes tend to drift (as described above).

doc1 = ActiveDocument.Name
Documents.Add
doc2 = ActiveDocument.Name
' Do something with document2
Documents(doc1).Activate
' Do something with document1
Documents(doc2).Activate
' Do something with document2 again
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top