If you want to find out the total number of lines in a file, you can simply do something like this :
VB Code:
Private Function getLineCount(ByVal strFilePath As String) As Long Open strFilePath For Binary As #1 Dim strBuff As String: strBuff = Space(Lof(1)) Get #1, , strBuff getLineCount = UBound(Split(strBuff, vbCrLf)) Close #1 End Function
But if you're dealing with very large text files, then something like that could take a very long time to complete.
So why not get an estimate on the number of lines ?
VB Code:
Private Function getLineCount(ByVal strFilePath As String) As Long Dim i As Long, lngTotalLengthSoFar As Long, lngAverageLength As Long Open strFilePath For Input As #1 Dim strBuff As String: strBuff = Space(LOF(1)) Dim strBuff2 As String: strBuff2 = vbNullString For i = 0 To 49 Line Input #1, strBuff2 lngTotalLengthSoFar = lngTotalLengthSoFar + Len(strBuff2) Next lngAverageLength = lngTotalLengthSoFar / 50 getLineCount = LOF(1) / lngAverageLength Close #1 End Function
The above code will take the first 50 lines, and estimate from that, the total number of lines in the file.
As with all statistical or analysis operations, the larger the source dataset the more accurate your results will be, so increasing the sample size from 50 to 100 or 200 would, on average, provide you with a more accurate result.
At the same time, if you don't require brilliant accuracy, or know that each line is a very similar length and want to get the job done quick, then one could reduce the sample from 50 to 10 or 20 etc.




Reply With Quote