Counting the actual number of records in a text file.

  • Thread starter Thread starter doyapore
  • Start date Start date
D

doyapore

Dear All,
This is a follow-up of my post dated 25/12/2004.
Can someone tell me a way of counting the number of records stored in a text
file. The records in the text file are stored in the following manner:
1. Code_no: 10 character.
2. Card_slno: 10 character.
3. Amount: 10 character.
My intention is to count the number of records stored in the text file and
flash it onto a form before the actual import process is initiated.
I shall be grateful for your help.
 
In general, the only way to find the number of records in a text file is
to read it from beginning to end and literally count every record
separator, using something like this:

Public Function CountRecordsInTextFile(FileSpec As String) As Long
Dim lngFN As Long
Dim lngRecordCount As Long
Dim strBuffer As String

lngFN = FreeFile()
lngRecordCount = 0
Open FileSpec For Input As #lngFN
Do Until EOF(lngFN)
Line Input #lngFN, strBuffer
lngRecordCount = lngRecordCount + 1
Loop
Close lngFN
CountRecordsInTextFile = lngRecordCount
End Function

If (a) it's a fixed-width file and (b) the text encoding used has a
fixed number of bytes per character, it's also possible to calculate the
number of records by dividing the file size by the record size. For an
ANSI (one-byte) file, the number of bytes in a record equals the total
number of characters in all the fields plus 2 (except that the last
record may not have a terminating CRLF pair).
 
Dear All,
I have muddled my way through a solution. Please could you comment on the
same:
----------------------------------------------------------------------------
-------
Private Sub <name of the button>_Click()
Dim strFile As String
Dim hFile As Long
Dim strLine As String
Dim nCount As Long
Dim nCountMsg As String
'Get a new file handle
hFile = FreeFile

'Open the file for sequential access
strFile = "...full pathname with the file name..."
Open strFile For Input Access Read Shared As hFile

'Count the number of records in the file
'Print the file contents
nCount = 0
Do Until EOF(hFile)
Line Input #hFile, strLine
'Debug.Print strLine
nCount = nCount + 1
Loop

'Close the file
Close hFile

'Post the number of records in the message box
nCountMsg = "Total number of records is " + Chr(13) + Str(nCount)
MsgBox nCountMsg, vbOKOnly, "Record Count in the Text File"

End Sub
 
Thanks John. Your solution, I think, ratifies my approach to the problem.
Thank you once again.
 
Back
Top