Reading Text file into an array

G

gw.boswell

I want to read an ASCII text file that contains variable length lines
into an array. I can read the file a line at a time or a character at
a time but what I really need is to read the text between delimiters
as a unit. Is there an end of line marker (similar to the EOF
marker)? How do I capture the information between delimiters?

TIA
Garry
 
R

RB Smissaert

Read your whole text file and put it in a string variable.
Then split the string with the Split function of whatever
delimiter you choose.

RBS
 
G

Guest

the end of line marker in windows is two characters together. In VBA is is
represented with the constant: vbCrLf

But that would be the same as reading it in a line at a time which you say
you can do.
If you actually want to parse a delimited file, then Chip Pearson has sample
code for that:

http://www.cpearson.com/excel/imptext.htm import/export text files
 
G

gw.boswell

Read your whole text file and put it in a string variable.
Then split the string with the Split function of whatever
delimiter you choose.

RBS







- Show quoted text -

I'll give that a shot. To load the array how do I locate the end of
the string in which I have placed the file info?
 
R

RB Smissaert

Get the file into a string variable with something like this:

Function OpenTextFileToString(strFile As String) As String

Dim hFile As Long

'obtain file handle, open file
'and load into a string buffer
hFile = FreeFile

Open strFile For Input As #hFile

OpenTextFileToString = Input$(LOF(hFile), hFile)

Close #hFile

End Function


Then you can do something like this:

Sub test()

Dim strString As String
Dim arr

strString = OpenTextFileToString("C:\test.txt")

arr = Split(strString, vbCrLf)

End Sub


Replace the vbCrLf with whatever your delimiter is.


RBS
 
G

gw.boswell

Get the file into a string variable with something like this:

Function OpenTextFileToString(strFile As String) As String

Dim hFile As Long

'obtain file handle, open file
'and load into a string buffer
hFile = FreeFile

Open strFile For Input As #hFile

OpenTextFileToString = Input$(LOF(hFile), hFile)

Close #hFile

End Function

Then you can do something like this:

Sub test()

Dim strString As String
Dim arr

strString = OpenTextFileToString("C:\test.txt")

arr = Split(strString, vbCrLf)

End Sub

Replace the vbCrLf with whatever your delimiter is.

RBS







- Show quoted text -

Excellent. I used the tab (Chr(9)) which is the delimiter for this
ASCII file and it worked great. Thanks for the good advice.
 

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