It is often useful to read a file line by line, especially if you need to parse the file if you have created your own special file format. Please note that this method is slower than reading the file all at once, so only use it if you really need to load the file line by line!
Dim nFileNum As Integer, sText As String, sNextLine As String, lLineCount
As Long
' Get a free file number
nFileNum = FreeFile
' Open Test.txt for input. App.Path returns the path your app is saved in
Open App.Path & "Test.txt" For Input As nFileNum
lLineCount = 1
' Read the contents of the file
Do While Not EOF(nFileNum)
Line Input #nFileNum, sNextLine
'do something with it
'add line numbers to it, in this case!
sNextLine = lLineCount & " " & sNextLine
& vbCrLf
sText = sText & sNextLine
lLineCount = lLineCount + 1
Loop
TextBox1.Text = sText
' Close the file
Close nFileNum
Note that the Line Input function returns the current line to sNextLine. This does not include the new line character, so if you are displaying the text you need to add one!
Comments