ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Help with Open and Read txt file, please? (https://www.excelbanter.com/excel-programming/328276-help-open-read-txt-file-please.html)

Ed

Help with Open and Read txt file, please?
 
Myrna and Dick helped me get started on trying to open a .txt file. 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



Bill Renaud[_2_]

Help with Open and Read txt file, please?
 
Ed,

You might have to declare another variable to refer to a Text Stream object,
then include an additional line of code to open the file that way. Also, you
should use the AtEndOfStream property on the Text Stream object to prevent
running past the end of the file. Also, how do you plan to read multiple
lines of text file into a single Contents variable? Each line would probably
have to be added with a NewLine string (vbNewLine) (or vbCrLf) embedded
between it and the previous contents.

So your code (untested revision) might look like the following:

Dim FSO As Object, File As Object, Contents As String
Dim TS as Object
'Text Stream object.
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)
Set TS = File.OpenAsTextStream(1, 0) 'Open the text file for reading in
ASCII format.

Contents = ""
Do While Not TS.AtEndOfStream
Contents = Contents & TS.ReadLine & vbNewLine
Loop

TS.Close

'Now do something with Contents.
--
Regards,
Bill




All times are GMT +1. The time now is 01:16 PM.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
ExcelBanter.com