Reading from Text Files
Reading from an existing file is a very simple extension of the code example we used in Working with Text Files, except this time we will utilise the ReadLine function of the TextStream object from FileSystemObject to return a string containing the first line from our file.
Reading the First Line of Text
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Set fsoStream = fso.OpenTextFile(strFileName, ForReading)
With fsoStream
End With
If everything worked you will get the following message. If not, make sure that your text file exists and that it has at least one line of text.

Of course in most cases we want to read more than just the first line of the file. For this we add a simple Do While…Loop and reference the property AtEndOfStream which tells us that the end of the file has been reached. Normally we would read each line and run some kind of actions on it, such as adding it to the database or checking the value against some previously stored values – feel free to add these at the TODO line.
Reading Every Line of Text
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream
Set fsoStream = fso.OpenTextFile(strFileName, ForReading)
With fsoStream
Do While Not .AtEndOfStream
Loop
End With
Other Topics about Using the FileSystemObject
Getting Information About Your Drives
Getting Information About Your Folders
Getting Information About Your Files
Working with Text Files
|