Bla*_*ail 5 excel vba counter row excel-vba
我有超过100个文本文件,我必须计算每个文本的行数.Column A
列出文件名,位于指定的文件夹中E1
.有几个文件有超过100万行,导致脚本运行的时间非常长.
Sub counter()
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim longtext As String
Dim lines As Variant
Dim GoToNum As Integer
Dim Start As Integer
GoToNum = 2
Start = 3
Do Until IsEmpty(Cells(Start, 1))
GoToNum = GoToNum + 1
Start = Start + 1
Loop
For i = 3 To GoToNum
If Cells(i, 2).Value <= Cells(2, 5).Value Then
ConOrg = Cells(1, 4).Value & "\" & Cells(i, 1).Value
Set ts = fso.OpenTextFile(ConOrg, ForReading, False)
longtext = ts.ReadAll
ts.Close
lines = Split(longtext, vbLf)
Cells(i, 3) = UBound(lines) - LBound(lines) - 1
End If
Next i
End Sub
Run Code Online (Sandbox Code Playgroud)
如何获取最后一行的数字(来自文本文件)以避免逐行计数?
40 MB文件(170万行)
- CountLF
= 25.2秒
- CountLines
= 2.1秒
14个B档(6行)×10,000倍
- CountLF
= 1.3秒
- CountLines
= 18.9秒
Function countLF(fName As String) As Long
Dim st As String
Open fName For Input As #1: st = Input(LOF(1), 1): Close #1
countLF = Len(st) - Len(Replace(st, vbLf, "")) + 1
End Function
Run Code Online (Sandbox Code Playgroud)
用法示例:
Debug.Print countLF("c:\test.txt")
Run Code Online (Sandbox Code Playgroud)
Function countLines(fName As String) As Long
countLines = CreateObject("Scripting.FileSystemObject").OpenTextFile(fName, 8, True).Line
End Function
Run Code Online (Sandbox Code Playgroud)
用法示例:
Debug.Print countLines("c:\test.txt")
Run Code Online (Sandbox Code Playgroud)
更多基准测试: (2500个小文本文件)
二进制访问/获取 (4.32s)杀死= 1.17s...打开F进行二进制访问读取为#1:ReDim ...获取#1
,,,字节行输入/ LineInput (4.44s)Kill = 1.11s...打开F输入为#iFile ...行输入#1,st
Early Bind/ReuseObj (5.25s)Del = 1.12s...设置o = New Scripting.FileSystemObject':st = o.OpenTextFile(F).ReadAll()
Early Bind/FreshObj(11.98s)Del = 1.35s...设置o = New Scripting.FileSystemObject':st = o.OpenTextFile(F).ReadAll()
LateBind/ReuseObj (6.25s)Del = 1.47s...设置o = CreateObject("Scripting.FileSystemObject")
LateBind/FreshObj (13.59s)Del = 2.29s...使用CreateObject("Scripting.FileSystemObject")
归档时间: |
|
查看次数: |
2756 次 |
最近记录: |