Count Lines in File

The code below counts the number of lines in a file. Simply call the CountLines procedure, passing the file name in its parameter

Function CountLines(ByVal strFilePath As String) As Integer

       '     'delcare variables
       Dim fileFile As Integer
       Dim intLinesReadCount As Integer
       intLinesReadCount = 0
       '     'open file
       fileFile = FreeFile

              If (File_Exists(strFilePath)) Then
                     Open strFilePath For Input As fileFile
                           'file doesn't exist
                     MsgBox "File: " & strFilePath & " hasn't been downloaded yet. Preprocessing is being aborted.", MB_OK, "File Does Not Exist"
                     Count_Lines_In_File = -1
                     Exit Function
              End If

             'loop through file
       Dim strBuffer As String

              Do While Not EOF(fileFile)
                           'read line
                     Input #fileFile, strBuffer
                           'update count
                     intLinesReadCount = intLinesReadCount + 1

             'close file
       Close fileFile
             'return value
       Count_Lines_In_File = intLinesReadCount
End Function
Function File_Exists(strFilePath As String)
    If Dir(strFilePath, vbNormal + vbHidden + vbSystem + vbReadOnly) = "" Then
        File_Exists = False
        File_Exists = True
    End If
End Function

You might also like...


James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” - Brian Kernighan