Excel テキストファイル読み込みを TextStream で劇的に高速化した
条件:文字数 85万文字
before 4分 after 0.4秒
当初の1行処理 文字数 85万 で 4分
Public Function ReadTextFile(ByVal sFilePath As String, _
ByRef strResult As String, _
Optional blnVBCRLF As Boolean = False) As Boolean
Dim buf As String, Cnt As Long
On Error GoTo myErr
Cnt = 0
Open sFilePath For Input As #1'"C:\Work\Sample.txt"
Do Until EOF(1)'EOFまで1行ずつ転記する
Line Input #1, buf
If blnVBCRLF = True Then
strResult = strResult & buf & vbCrLf
Else
strResult = strResult & buf
End If
Cnt = Cnt + 1
If Cnt Mod 5000 = 0 Then
Sleep 25
DoEvents
Sleep 25
End If
Loop
Close #1'注意:Closeしないと 次回からOpen できない
MyExit:
ReadTextFile = True
Exit Function
myErr:
ReadTextFile = False
End Function
TextStream で読み込み 同条件 85万文字で0.4秒 !
Public Function ReadTextFileStream(ByVal sFilePath As String, _
ByRef strResult As String) As Boolean
Dim buf As String
With CreateObject("Scripting.FileSystemObject")
With .GetFile(sFilePath).OpenAsTextStream
buf = .ReadAll
.Close
End With
End With
MyExit:
strResult = buf
ReadTextFileStream = True
Exit Function
myErr:
ReadTextFileStream = False
End Function