Visual Basic For Applications: Read a text file

Platform:Visual Basic For Applications
Task:Read a text file
Discussion:
The following sub will read a text file line by line and output the contents to the immediate window.
Example:
Public Sub ReadFile(FileToRead As String)
    'Call this as follows: ReadFile "C:\MyTextFile.txt"
    Dim fso
    Set fso = CreateObject("Scripting.FileSystemObject")

    Dim oFS
    Set oFS = fso.OpenTextFile(FileToRead)
    Do Until oFS.AtEndOfStream
        Debug.Print oFS.ReadLine
    Loop
End Sub
Back to Index