count number of lines in a file

hi everyone, is it possible to count the number of lines in a file?
I'm using:

    Dim strTemp As String * 1
    Dim i As Integer
    i = 0
    Open App.Path & "\aras.pol" For Input As 1#
    Do Until EOF(1)
    i% = i% + 1
    Line Input #1, strTemp
    Close #1

msgbox "number of lines: " & i

this works but is there another way?
Who is Participating?
stefriConnect With a Mentor Commented:
You can create a file system object
Open the file
Read all lines in a string
use split to cut the string at every vbcr or vblf or vbcrlf
the number of lines will be the upperbound of the array -1
Going to line N would be array(N-1)

This code has been tested in Excel VBA

Option Explicit

Function numLines (theFile) As Long

  Const ForReading = 1, ForWriting = 2
  Dim fso As Object, f As Object
  Dim allLines As String
  Dim linesSplit() As String

  Set fso = CreateObject("Scripting.FileSystemObject")

  Set f = fso.OpenTextFile(theFile, ForReading)
  allLines = f.ReadAll

  linesSplit = Split(allLines, vbCrLf)
  numLines = UBound(linesSplit) - 1
  Set f = Nothing
  Set fso = Nothing
End Function

Sub test()
Dim n As Long

n = numLines ("c:\setuplog.txt")

End Sub

igfpAuthor Commented:
oh, and also to go to a specific line. I'm using the same thing but when i= "number of the line I want" then it exits the cycle. Is there another way to do this as well?
Similar to stefri and yours, you can read the entire file in one shot, then "count" the number of newline characters.

dim strTemp as strnig
dim strLinesSplit() as string
dim iNumLines as integer

' read the entire file
Open App.Path & "\aras.pol" For Input As 1#
strTemp = input$(lof(1), #1)
Close #1

' count the number of newlines, then add one for the last line
strLinesSplit = Split(strTemp, vbNewLine)
iNumLines = UBound(linesSplit) - 1

The key here is the Input$ and the Split functions.
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

igfpAuthor Commented:
my question now is, since i like mine the best, wich one takes the points????
>is there another way
Since this Q was answered in the first comment (stefri), I think you should accept that as your answer.
igfpAuthor Commented:
as you wish! ;) Thank you both!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.