EziData Solutions

Web, NET and SQL Server

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

'open and read the contents of an existing file
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"

'declare the variables for use with the Scripting library
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream

'open an existing text file
Set fsoStream = fso.OpenTextFile(strFileName, ForReading)

'read a line to the file and display in a message box
With fsoStream

MsgBox .ReadLine

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.

Results of reading a simple text file

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

'open and read the contents of an existing file
Dim strFileName As String
strFileName = "C:\Temp\MyWorld.txt"

'declare the variables for use with the Scripting library
Dim fso As New Scripting.FileSystemObject
Dim fsoStream As Scripting.TextStream

'open an existing text file
Set fsoStream = fso.OpenTextFile(strFileName, ForReading)

'read a line to the file and display in a message box
With fsoStream

Do While Not .AtEndOfStream

'TODO: add some code here to process each line
MsgBox .ReadLine

Loop

End With

 

Posted: Nov 01 2006, 01:19 by CameronM | Comments (0) RSS comment feed |
  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: Access | VBA