19

Need a function that will accept a filename as parameter and then return the number of lines in that file.

Should be take under 30 seconds to get the count of a 10 million line file.

Currently have something along the lines of - but it is too slow with large files:

Dim objFSO, strTextFile, strData, arrLines, LineCount
CONST ForReading = 1

'name of the text file
strTextFile = "sample.txt"

'Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")

'Open the text file - strData now contains the whole file
strData = objFSO.OpenTextFile(strTextFile,ForReading).ReadAll

'Split by lines, put into an array
arrLines = Split(strData,vbCrLf)

'Use UBound to count the lines
LineCount = UBound(arrLines) + 1

wscript.echo LineCount

'Cleanup
Set objFSO = Nothing

8 Answers 8

30

If somebody still looking for faster way, here is the code:

Const ForAppending = 8
Set fso = CreateObject("Scripting.FileSystemObject") 
Set theFile = fso.OpenTextFile("C:\textfile.txt", ForAppending, Create:=True) 
WScript.Echo theFile.Line 
Set Fso = Nothing

Of course, the processing time depend very much of the file size, not only of the lines number. Compared with the RegEx method TextStream.Line property is at least 3 times quicker.

6
  • 1
    +1 This is definitely the best trick for this question! Thanks!
    – Kul-Tigin
    Feb 21, 2013 at 21:02
  • 5
    You might want to close the file in the end, and "Set oFso = Nothing" should be "Set fso = Nothing". I would also point out that 8 means "For appending", which is why it immediately reads to the end of the file.
    – Magnus
    May 1, 2014 at 18:17
  • 3
    Also, I would set the last argument to False, thus not creating the file if it does not exist, but instead allowing it to error out.
    – Magnus
    May 1, 2014 at 18:27
  • 4
    And use theFile.Line - 1 to return the number of lines that exist in the file, because theFile.Line returns the number of the line that you are about to write but which does not exist yet.
    – Magnus
    May 1, 2014 at 18:34
  • What I was looking for. Thank you! May 12, 2019 at 9:07
8

The only alternative I see is to read the lines one by one (EDIT: or even just skip them one by one) instead of reading the whole file at once. Unfortunately I can't test which is faster right now. I imagine skipping is quicker.

Dim objFSO, txsInput, strTemp, arrLines
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")

strTextFile = "sample.txt"
txsInput = objFSO.OpenTextFile(strTextFile, ForReading)

'Skip lines one by one 
Do While txsInput.AtEndOfStream <> True
    txsInput.SkipLine ' or strTemp = txsInput.ReadLine
Loop

wscript.echo txsInput.Line-1 ' Returns the number of lines

'Cleanup
Set objFSO = Nothing

Incidentally, I took the liberty of removing some of your 'comments. In terms of good practice, they were superfluous and didn't really add any explanatory value, especially when they basically repeated the method names themselves, e.g.

'Create a File System Object
... CreateObject("Scripting.FileSystemObject")
5
  • 2
    +1 I was about to post this myself and found it was twice as fast (1000000 lines in 5s). As an optimisation you can make the only thing in the loop filInput.ReadLine then when its done filInput.Line-1 will be the count of lines (so you avoid the counter & buffer variable)
    – Alex K.
    Sep 14, 2011 at 13:08
  • Good point! Will edit accordingly. Actually, don't even need to read the line. Can just skip it! Sep 14, 2011 at 13:43
  • Thanks! BTW I'm surprised you weren't the one to post a neat Regexp solution! Sep 15, 2011 at 11:33
  • @toop: Kul-Tigin's answer is (allegedly) faster than mine; if you can confirm this, then maybe you should accept his answer instead! Just being chivalrous... Sep 15, 2011 at 15:47
  • @Jean All answers were acceptable, doesn't matter which answer is accepted. You're already a chevalier in my sight :) Someone chooses the most appropriate one for himself.
    – Kul-Tigin
    Sep 15, 2011 at 16:38
7

Too large files...
The following is the fastest-effeciently way I know of:

Dim oFso, oReg, sData, lCount
Const ForReading = 1, sPath = "C:\file.txt"
Set oReg = New RegExp
Set oFso = CreateObject("Scripting.FileSystemObject")
sData = oFso.OpenTextFile(sPath, ForReading).ReadAll
With oReg
    .Global = True
    .Pattern = "\r\n" 'vbCrLf
    '.Pattern = "\n" ' vbLf, Unix style line-endings
    lCount = .Execute(sData).Count + 1
End With
WScript.Echo lCount
Set oFso = Nothing
Set oReg = Nothing
4
  • +1 Nice, I was waiting for someone to post a RegExp solution. You say it is faster... have you tested this? Sep 15, 2011 at 11:31
  • Yes, I've tested to a sample large file. boost's code tooks 28 secs, yours 22 secs. With the Regex, it tooks 8 secs only.
    – Kul-Tigin
    Sep 15, 2011 at 12:53
  • 1
    What do you mean by the comment in the commented-out line? UTF-8 encoded files (just as ISO-8859-1 or what not) can have WIndows or Unix style line endings. There is no relation.
    – mgr326639
    May 16, 2016 at 13:54
  • @mgr326639 yes I mean Unix style line-endings. thanks for the correction.
    – Kul-Tigin
    May 16, 2016 at 13:57
4

You could try some variation on this

cnt = 0
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(filespec, ForReading, False)
Do While theFile.AtEndOfStream <> True
   theFile.SkipLine
   c = c + 1
Loop
theFile.Close
WScript.Echo c,"lines"
1

Some of the above answers are good, but if a file cannot be opened for writing or appending this should work...

filePath = "C:\textfile.txt"
Set fso = CreateObject("Scripting.FileSystemObject") 
Set theFile = fso.OpenTextFile(filePath) 

theFile.skip fso.getfile(filePath).size
WScript.Echo theFile.Line
...
1
  • This is the second fastest of all the provided answers, tested on a file with 1,000,000 lines. The advantage of this solution is that you are opening the file for reading. The faster answer by k.move opens the file for appending, which might cause an error if the file is open for editing by another process.
    – Safwan
    Nov 11, 2023 at 13:03
-2
txt = "c:\YourTxtFile.txt"
j = 0
Dim read
Open txt For Input As #1
  Do While Not EOF(1)
    Input #1, read
    j = j + 1
  Loop
Close #1

If it adds an empty last line the result is (j - 1).

It works fine for one column in the txt file.

2
  • @Ekkehard.Horner Care to elaborate? At first glance, this looks legit to me. Dec 5, 2018 at 8:13
  • 1
    It's not VBScript and incrementing a counter if there is a .Line property is not right. Dec 5, 2018 at 14:17
-2

How to count all lines in the notepad Answers: => Below is the code -

Set t1=createObject("Scripting.FileSystemObject")
Set t2=t1.openTextFile ("C:\temp\temp1\temp2_VBSCode.txt",1)
Do Until t2.AtEndOfStream
strlinenumber = t2.Line
strLine = t2.Readline
Loop
msgbox strlinenumber
t2.Close
1
-3

I was looking for a faster way than what I already had to determine the number of lines in a text file. I searched the internet and came across 2 promising solution. One was a solution based on SQL thew other the solution I found here based on Fso by Kul-Tigin. I tested them and this is part of the result:

Number of lines  Time elapsed  Variant
--------------------------------------------------------
110              00:00:00.70   SQL
110              00:00:00.00   Vanilla VBA (my solution)
110              00:00:00.16   FSO    
--------------------------------------------------------
1445014          00:00:17.25   SQL
1445014          00:00:09.19   Vanilla VBA (my solution)
1445014          00:00:17.73   FSO

I ran this several times with large and small numbers. Time and again the vanilla VBA came out on top. I know this is far out of date, but for anyone still looking for the fastest way to determine the number of lines in a csv/text file, down here's the code I use.

Public Function GetNumRecs(ASCFile As String) As Long
  Dim InStream As Long
  Dim Record As String
  InStream = FreeFile
  GetNumRecs = 0
  Open ASCFile For Input As #InStream
  Do While Not EOF(InStream)
    Line Input #InStream, Record
    GetNumRecs = GetNumRecs + 1
  Loop
  Close #InStream
End Function
2
  • Um... isn't this code identical to that in Matt's answer posted right here a year earlier? Dec 5, 2018 at 8:13
  • 1
    Wrong language (VBA, not VBScript); wrong strategy (incrementing a counter instead of accessing a property of an object). Dec 5, 2018 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.