Skip to: Site menu | Main content

Login

Name: 
Password:
Remember me?
Register

Reading the Last X Lines From a Text File

written by Helen Toomik - Last updated Nov 2004

If you are working with very large text files, and only want to read the last few lines, looping through the whole file line by line until you get to the end can be very time-consuming. In that case it's better to open the file in binary mode, and work backwards from the end.

This function will open a file, and read the last x lines of text from it. It starts from the end of the file and searches for line breaks, working backwards until it's either found enough line breaks, or reached the beginning of the file.

Function LastXLines(Path As String, NumLines As Long) 
     
    Dim FF As Integer 
    Dim lngCounter As Long 
    Dim lngPos As Long 
    Dim strData As String 
     
    FF = FreeFile 
     'we are looking for 2 characters occurring together: vbCr & vbLf
     'so we make a 2-character buffer
    strData = Space$(2) 
    Open Path For Binary As #FF 
     'start at the end of the file
    lngPos = LOF(FF) 
     
    Do Until lngCounter = NumLines Or lngPos = 1 
         'take one step back
        lngPos = lngPos - 1 
         'get 2 characters
        Get #FF, lngPos, strData 
         'is it a new line?
        If strData = vbCrLf Then lngCounter = lngCounter + 1 
    Loop 
     
     'move past the last found vbCrLf
    If lngPos > 1 Then lngPos = lngPos + 2 
     'make space in the string for the rest of the file
    strData = Space$(LOF(FF) - lngPos + 1) 
     'read the data
    Get #FF, lngPos, strData 
    Close #FF 
    LastXLines = strData 
     
End Function