Inserting text from a text file into Word

A

aef1

Please would someone know how to enter text from a text file (the whole
file contents) into Word. I have seen some code on the forums, but
don't understand how it works.

Found this simple code, but it will only input the last set of
characters in the file.


Dim MyString
Open "C:\files\test.txt" For Input As #1
Do While Not EOF(1)
Input #1, MyString
Loop
Close #1


ActiveDocument.Bookmarks("Test").Range.Text = MyString


Thanks in advance,
Net
 
J

Jay Freedman

If you want to do it this way, you have to collect the lines as they're read
from the file and append them to a string:

Dim tempString, MyString
Open "C:\files\test.txt" For Input As #1
Do While Not EOF(1)
Input #1, tempString
MyString = MyString & tempString & vbCr
Loop
Close #1
' remove last vbCr
MyString = Left(MyString, Len(MyString) - 1)

ActiveDocument.Bookmarks("Test").Range.Text = MyString

But you can do the whole thing in one step with the InsertFile command:

ActiveDocument.Bookmarks("Test").Range.InsertFile _
FileName:="c:\files\test.txt"

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
T

Tony Jollans

Oops - seems like I was (or will be) posting from the future.

I have corrected it but am using Windows Mail on Vista Beta 2 so it may go
wrong again.
 
A

aef1

Thank you so much Jay!

The one step is great. I tried it and it worked fine for what I wanted
to do.
 
T

Tony Jollans

What your code is doing is reading the file line by line into the variable
'MyString', each line replacing the previous one. At the end you write the
contents of 'MyString', then containing the last line as you have seen, to
your bookmark.

You could shift the moving text to your document inside the loop and
continue line by line but you would need to alter it slightly to work
properly with the bookmark, or ...

... you could do the whole thing more easily with ...

ActiveDocument.Bookmarks("Test").Range.InsertFile
FileName:="C:\files\test.txt", Link:=False
 

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