View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
tlavedas tlavedas is offline
external usenet poster
 
Posts: 3
Default number of lines and characters in a text file

Peter T wrote:
There's LOF for characters (or FileLen if closed) but I don't know a direct
way to get the line count. Unless the file is very large I wouldn't think
using EOF would take so long but have a go with this -

Sub test()
Dim cntLen As Long, cntChars As Long, cntLines As Long
Dim sFile As String
Dim FF As Integer

sFile = "C:\temp\test.txt"
cntLen = FileLen(sFile)

FF = FreeFile
Open sFile For Input As #FF
Seek FF, 1
cntChars = LOF(FF)
cntLines = UBound(Split(Input(cntChars, FF), vbCrLf)) + 1
Close #FF

' cntChars will include returns
Debug.Print cntLines, cntChars, cntLen
End Sub

Regards,
Peter T


"Bob Flanagan" wrote in message
...
Is there a way to get the number of lines and characters in a text file
without opening it in Excel or via reading each line until EOF is reached?

Bob


This approach uses the scripting FileSystemObject, instead ...

Const ForAppending = 8
Dim sFile, nLines

sFile = "D:\Someplace\Filename.txt"
with CreateObject("Scripting.FileSystemObject")
nLines = .OpenTextFile(sFile, ForAppending).Line
nChrs = .GetFile(sFile).Size
end with

This approach doesn't actually count the number of characters (new
characters omitted), but rather the file's size. This, BTW, is not the
size of the file on the disk, since that is in increments of the disk's
'cluster block size'.

And, I am told some unusual file conditions (empty file and files of
blank lines only) can yield inaccurate results for the line count (off
by one line).

Tom Lavedas
===========