Arun
Arun

Reputation: 27

Switching between two newly created Word Documents through Excel Vba is not happening

I have created two new Word Documents through Excel vba, which was not yet saved. The documents were created as "Document1" and "Document2". When I try to switch between documents, I get Bad File name error 4160 for Document2. Please help me in resolving this issue.

Sub DocSwitch()

Dim s As Object

Set s = Word.Application.Selection

Documents("Document1").Select

s.TypeText Text:="Hello"

Documents("Document2").Select

s.TypeText Text:="Hi"


End Sub

Upvotes: 0

Views: 641

Answers (1)

Charles Kenyon
Charles Kenyon

Reputation: 1026

When you create the documents, assign them to a document variable.

Dim WordApp as application
Set WordApp = Word
Dim MyDoc1 as Document
Dim MyDoc2 as Document

Set MyDoc1 = WordApp.Documents.Add
Set MyDoc2 = WordApp.Documents.Add

The above code was just typed here on-the-fly and may need some adjustment, but should give you the idea. Then, in your code, use your variables to refer to particular documents.

So, rather than referring to Documents(Document1) you would refer to MyDoc1.

Upvotes: 0

Related Questions