【问题标题】:Why is the result 1, when I count the lines of the text?当我计算文本的行数时,为什么结果为 1?
【发布时间】:2018-06-11 17:15:33
【问题描述】:

最初我在 A 列(在 excel 中)中有一个文本文件名称列表,我想浏览所有文件以打开并计算其行数。当我在下面运行脚本时,计数器结果是 '1'

当我使用 Notepad++ 或 Sublime Text 打开文本文件时,我看到文件的行位于不同的行中。但是当我用记事本打开文件时,我会在一行中看到整个文本。在这种情况下有什么问题,我该如何解决。 (行分隔符是 '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
    Loop

    Cells(1, 1).Value = counter

    Close #1

End Sub

我必须对超过 100 个文本文件进行计数。

【问题讨论】:

  • 您的子 counter 与您的变量 counter 同名,这不是一个好主意。还有没有For 循环的Next i
  • Open FilePath For Input 只识别 CRLF 而不是 LF 作为换行符。 • 可能与Loading linux text file into excel using VBA 重复
  • 我的错,复制粘贴错了。

标签: excel count line vba


【解决方案1】:

您可以使用文本流:

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
    ts.Close
    lines = Split(longtext, vbLf)
    Cells(1, 1) = UBound(lines) - LBound(lines) + 1

End Sub

您需要设置对 Microsoft Scripting Runtime 的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2023-02-07
    • 2019-11-18
    • 2017-05-22
    相关资源
    最近更新 更多