我正在加速處理一個非常大的文本文件(〜100兆左右)。我謹慎使用redim preserve調用,但仍然需要5分鐘左右才能運行。該文本文件基本上是分析報告,我試圖解析出來。我只能訪問大文件。什麼是一個人要做什麼。 VBA只是慢嗎?這裏是代碼,「報告」對象是我創建的類。大多數報告都只是一個幾百行,所以這就是爲什麼我選擇1000爲UBOUND:用VBA快速處理大文本文件
Public Function GetPages(originalFilePath As String) As Collection
Dim myReport As report
Dim reportPageCollection As Collection
Dim startLine As Long
Dim endLine As Long
Dim fso As FileSystemObject
Dim file As textStream
Dim lineStr As String
Dim index As Long
Dim lines() As String
Set fso = New FileSystemObject
Set reportPageCollection = New Collection 'initialize the collection
Set file = fso.OpenTextFile(originalFilePath, ForReading)
ReDim lines(0 To 1000)
lineStr = file.ReadLine 'skip the first line so the loop doesnt add a blank report
lines(0) = lineStr
index = 1
Do Until file.AtEndOfLine 'loop through from the startline to find the end line
lineStr = file.ReadLine
If lineStr Like "1JOBNAME:*" Then 'next report, so we want to return an array of the single line
'load this page into our report page collection for further processing
Set myReport = New report
myReport.setDataLines = lines() 'Fill in 'ReportPage' Array
reportPageCollection.Add myReport 'add our report to the collection
'set up array for new report
ReDim lines(0 To 1000)
index = 0
lines(index) = lineStr
index = index + 1
Else
'============================ store into array
If index = UBound(lines) Then
ReDim Preserve lines(0 To UBound(lines) + 1000)
lines(index) = lineStr
index = index + 1
Else
lines(index) = lineStr
index = index + 1
End If
'============================
End If
Loop
file.Close
Set fso = Nothing
Set GetPages = reportPageCollection
端功能
任何幫助表示讚賞。謝謝!
該文件在網絡驅動器上,但我沒有提到我先將其複製到本地驅動器,然後纔開始讀取它。我會試試這個。謝謝! – Fink 2009-09-29 13:38:51
非常棒!對於150兆字節的文件,採用<10秒。不太確定之前爲什麼這麼慢。現在來調整其他功能。 – Fink 2009-09-29 14:09:59