Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading A File

Status
Not open for further replies.

campbere

Technical User
Oct 10, 2000
146
US
Is there a way to read from the file the number of lines it has?

I have a file that looks like this:

Product Y
Product Q
Product Quy
Product Tew
Product R32
Product Te4

I want to be able to read the file and and count the number of items. In this case it would be 6.

Does anyone know if this is possible?
 
This is from MSDN. You might be able to put a counter in the loop. You can count the number of lines and feed the info into seperate varibles.

Dim TextLine
Open "TESTFILE" For Input As #1 ' Open file.
Do While Not EOF(1) ' Loop until end of file.
Line Input #1, TextLine ' Read line into variable.
Debug.Print TextLine ' Print to the Immediate window.
Loop
Close #1 ' Close file.
 
The above with a counter:
Code:
Dim sTmp As String, iLines As Long
Open "C:\YourFile.abc" For Input As #1
    iLines = 0
    Do While Not EOF(1)
        Line Input #1, sTmp
        iLines = iLines + 1
    Loop
Close #1
MsgBox "There are " & iLines & " lines in the file."
 
Why count for yourself? Let the FileSystem itself do the job:

Dim objFso As FileSystemObject
Dim objTs As TextStream

dim strFileName as String
strFileName = "C:\YourFile.abc"

Set objFso = New FileSystemObject
Set objTs = objFso_OpenTextFile(strFileName, ForReading)

Do While Not objTs.AtEndOfStream
objTs.SkipLine
Loop


'Line returns the current linenumber in the text (starting at 1)
' To detect the EndOfStream condition, the last Line was skipped,
' Therefore, decrement the number by 1


intNumberOfLines = objTs.Line - 1

objTs.Close

Set objTs = Nothing
Set objFso = Nothing


The FileSystemObject is part of scrrun.dll. It can be added to your project through the Project Menu: > References > Scripting Runtime Library.
If not installed, it can be downloaded from:
It is rather good (albeit somewhat slower than "old" file handling functions) at handling Text Files.
_________________________________
In theory, there is no difference between theory and practice. In practice, there is. [attributed to Yogi Berra]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top