How to count number of lines in a .CSV file in Visual Basic for Applications (VBA)

CWC
2 Min Read

First of all I would like to tell that there is no ‘count records’ function in VBA I am aware of and even though I prefer to use shell script I couldn’t find one in there either.

So in similar cases I have need to open the file, read through all the rows and updated a counter for all the non-blank ones, then closed it before processing. It slows down the end to end but is the only way I could find:

Open  For Input As #1
 NumRec = 0
 Do While Not EOF(#1)
     Line Input #1, record
     If record <> "" Then NumRec = NumRec+1
 Loop
 Close #1

If the data on the last line reflects the number of lines or something meaningful about the progress you are measuring, then you can do the following:

  1. Open the file as Binary
  2. Use the Seek statement to position near the end of the file, enough to capture the entire last record
  3. Input the characters to the end-of-file
  4. Split the string
  5. Process/inspect the data on the last record

For too large CSV file

If the file is too large, you can read ‘chunks’ of the file, split the chunk, and count the ‘lines’

With each iteration, you have to prepend the last item of the previous iteration’s Split() result to the current iteration’s ‘chunk’

The simplest way would be to read the entire file into a string variable, use the Split() function on the end-of-line character(s), and then use the Ubound() function to see how large the resulting array is.  Only applicable when you have enough physical memory to hold the file contents and the Split() results without paging.

You can use the FileSystemObject/TextStream to read the file, using the SkipLine method, until you reach the end.  The TextStream Line property will tell you the last line, or you could just count the number of times you invoked the SkipLine method.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version