How to read a textfile line by line in VBA

To read a textfile line by line in VBA you can use the following snippet.
To read a textfile complete into a string you can use How to read a textfile in VBA.

Sample VBA

public sub ReadTextFileLinebyLine()
    Dim sFileName As String
    Dim iFile As Integer
    Dim sLine As String

	on error goto errorhandler
    sFileName = "C:\Users\Codesnippets\Desktop\Test.txt"
	
	If Len(Dir$(sFileName)) = 0 Then
        Exit Sub
    End If

    iFile = FreeFile()
    Open sFileName For Input As iFile

    Do While Not EOF(iFile)
        Line Input #iFile, sLine
        Debug.Print sLine 
    Loop

    Close iFile
	exit sub
	
errorhandler:
'handle the error your way
End Sub

One thought on “How to read a textfile line by line in VBA

Leave a Reply