Home » excel » excel – Why is the result 1, when I count the lines of the text?

excel – Why is the result 1, when I count the lines of the text?

Posted by: admin May 14, 2020 Leave a comment


Originally I have a list of name of text files in the column A (in excel), and I want to go through all files to open and count its rows. When I run the script below the counter result is ‘1

When I open the text files with Notepad++ or Sublime Text I see the lines of the file in different rows. But when I open the files with Notepad I see whole text in one row. What is the problem in this case and how can I fix it. (The line divider is ‘LF‘.)

Sub counting()

    Dim FilePath As String
    Dim counter As Integer
    Dim curLine As String

    FilePath = "C:\Users\kornel.fekete\Desktop\test\Test.txt"

    Open FilePath For Input As #1

    Do While Not EOF(1)
        counter = counter + 1
        Line Input #1, curLine

    Cells(1, 1).Value = counter

    Close #1

End Sub

I have to do this counting with more than 100 text files.

How to&Answers:

You could use a textstream:

Sub counting()

    Dim fso As New FileSystemObject
    Dim ts As TextStream
    Dim longtext As String
    Dim lines As Variant

    Set ts = fso.OpenTextFile("C:\Users\kornel.fekete\Desktop\test\Test.txt", ForReading, False)
    longtext = ts.ReadAll
    lines = Split(longtext, vbLf)
    Cells(1, 1) = UBound(lines) - LBound(lines) + 1

End Sub

You need to set a reference to Microsoft Scripting Runtime.