0
votes

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
1
Set s = Word.Application.Selection - once you do this, s points at whatever was selected when that line ran, and doesn't dynamically update when you select something else. You'll need to repeat the line if you activate a different document. - Tim Williams
Hi Tim Williams, the program doesn't proceed to the second s.TypeText, it gives bad file name error on Documents("Document2"). - Arun
Which exact line do you get the error? Is it possible your documents are in different instances of Word? - Tim Williams
Moreover, why are you switching focus from one document to another and using Select? You can directly address either document without doing so. See, for example: stackoverflow.com/questions/56251088/…, stackoverflow.com/questions/61051991/… & stackoverflow.com/questions/64853079/… - macropod
Tim Williams: I got error line "Documents("Document2").Select". They are created from two different macros of same Excel file. As Charles said, assigning document variables to each new documents solved the issue. macropod: I am new to word vba & learning.., Thanks for your valuable links. - Arun

1 Answers

0
votes

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.