562 attributed reviews in the last 3 years
Refreshingly small course sizes
Outstandingly good courseware
Whizzy online classrooms
Wise Owls only (no freelancers)
Almost no cancellations
We have genuine integrity
We invoice after training
Review 30+ years of Wise Owl
View our top 100 clients
Search our website
We also send out useful tips in a monthly email newsletter ...
Reading and writing to/from a text file using TextStreams Part three of a three-part series of blogs |
---|
The easiest way to work with text files in VBA is using TextStream objects - this blog explains how they work.
This blog is part of a complete Excel VBA tutorial, but we also run classroom training courses in VBA. |
Having created a text file (as per the previous part of this blog), here's some code to read it in. The trick is to keep reading lines until we reach the end of the text stream:
Sub ReadFile()
'again, we need this strange thing to exist so that ...
Dim fso As New FileSystemObject
'the file we're going to read from
Dim ts As TextStream
'... we can open a text file with reference to it
Set ts = fso.OpenTextFile("C:\Wise Owl\info.txt", ForReading)
'keep reading in lines till no more
Dim ThisLine As String
Dim i As Integer
i = 0
Do Until ts.AtEndOfStream
ThisLine = ts.ReadLine
i = i + 1
Debug.Print "Line " & i, ThisLine
Loop
'close down the file
ts.Close
End Sub
Here's what this would show in the immediate window:
The routine prints out the lines to the immediate window
When you choose to open a text file, you can do it in one of 3 ways:
The 3 possible ways to open a text stream
In our example we wanted to read from the file, but you can also use the OpenTextFile method to open a file to write more lines to it (using ForAppending).
Parts of this blog |
---|
|
Some other pages relevant to the above blogs include:
Kingsmoor House
Railway Street
GLOSSOP
SK13 2AA
Landmark Offices
99 Bishopsgate
LONDON
EC2M 3XD
Holiday Inn
25 Aytoun Street
MANCHESTER
M1 3AE
© Wise Owl Business Solutions Ltd 2023. All Rights Reserved.