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
Tony Jollans - 01 Nov 2006 18:53 GMT
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
--
Enjoy,
Tony
> 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
[quoted text clipped - 14 lines]
> Thanks in advance,
> Net
Tony Jollans - 01 Nov 2006 19:55 GMT
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.
--
Enjoy,
Tony
> 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
[quoted text clipped - 32 lines]
>> Thanks in advance,
>> Net
aef1@lycos.co.uk - 02 Nov 2006 10:39 GMT
Thank you so much Jay!
The one step is great. I tried it and it worked fine for what I wanted
to do.
Jay Freedman - 01 Nov 2006 18:58 GMT
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"

Signature
Regards,
Jay Freedman
Microsoft Word MVP FAQ: http://word.mvps.org
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
> 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,
[quoted text clipped - 14 lines]
> Thanks in advance,
> Net