Help to Open, Read a txt file?

E

Ed

I'm trying to open a .txt file and read the contents into a string. If I
hard-code the file path and name, I can use Shell to open it. But then I
can't read the contents into a string. So I was trying to use Open And Read
or ReadLine through the FSO. I guess the FSO is opening the file - it never
becomes visible (which is okay), but the code drops to the Read line. But
with either ReadLine or ReadAll, it errors out - "Input past end of file".
Can someone shed some light, please?

Ed

Dim FSO As Object, File As Object, Contents As String
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim strFName As String
Dim strFPath As String
strFPath = ActiveWorkbook.Path & "\"
strFName = strFPath & "About.txt"

Set File = FSO.OpenTextFile(strFName)
Contents = File.ReadLine
MsgBox Contents
 
J

Jay Freedman

Sorry, Ed, I can't reproduce your problem.

I assume from the reference to ActiveWorkbook that you're doing this in
Excel, so I tried it there as well as modifying it to run in Word. Whether I
used ReadLine or ReadAll, it just worked. It didn't matter whether the text
file did or didn't contain any newline characters.

I wonder whether your text file is damaged in some way or contains some
strange characters that are confusing the FSO. Other than that, I can't
think of any way to get that error from this code.
 
E

Ed

Jay, thanks for your help. Yes, I was trying it in Excel. And I think the
problem was as I was stepping through it and going back and forth to check
things, I somehow got off the active file, which gave me an incorrect
strFPath. Isolating just the read part worked fine. (VBA needs an error
code for "Operator head not firmly attached"!)

Ed
 
C

Chuck

Check out the Open Statement in VBE help, eg
Open "c:\yourfile.txt" For Input As #1
There's a lot to learn about there.
 

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