557 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 two 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. |
The code on this page will create a new text file on your hard disk:
The code will create the file called info.txt on your hard disk.
Here's what the contents of the text file will look like:
The code will write out the two lines!
The first thing we need to do is to create a reference to the Microsoft Scripting Runtime object library, and then create a FileSystemObject - refer to my separate FileSystemObject blog for how to do this and what it means:
Sub CreateFile()
'we need this, even though it doesn't make much sense!
Dim fso As New FileSystemObject
To do this, apply the CreateTextFile method to the weird FileSystemObject:
'the file we're going to write to
Dim ts As TextStream
'open this file to write to it
Set ts = fso.CreateTextFile("C:\Wise Owl\info.txt", True)
In this case, the second argument True refers to whether we'll overwrite any existing version of the file when we create the new one. We choose to do so.
You can use the WriteLine method to write lines of text, but you must then close the file:
'write out a couple of lines
ts.WriteLine ("If anyone finds this file")
ts.WriteLine ("they will wonder who created it")
'close down the file
ts.Close
End Sub
Here's the entire routine for ease of copying and reference:
Sub CreateFile()
'we need this, even though it doesn't make much sense!
Dim fso As New FileSystemObject
'the file we're going to write to
Dim ts As TextStream
'open this file to write to it
Set ts = fso.CreateTextFile("C:\Wise Owl\info.txt", True)
'write out a couple of lines
ts.WriteLine ("If anyone finds this file")
ts.WriteLine ("they will wonder who created it")
'close down the file
ts.Close
End Sub
Now that we've successfully created a text file, how can we read it in? To do this, we need to open another TextStream object, as shown in the final part of this blog.
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.