VBA学习笔记(四):VBA操作文本文件对比(FileSystemObject和OpenText)
通过本人对一下两种VBA文本处理方法效率的比较发现:使用OpenText方式读取文本文件的效率略高于FileSystemObject方式读取文本文件。
实验环境:
1)Excel2013 64bit。
2)Win7 64bit / SSD硬盘 / i7-4900MQ cpu @ 2.80GHz / 16G内存。
3)读取1.08G文本文件。
实验结果:
FileToOpenTxt方法耗时30.81s,
FileSsytemObject方法耗时36.69s.
方法一的效率比方法二高19.08%左右。
样本链接:
程序界面:
一、使用FileToOpenTxt方式读取文本文件,参考代码如下:
Sub OpenTxtInput() '选择文件,可以同时选择多个 FileToOpenTxt = Application.GetOpenFilename("文本文档(*.txt;*.FMT),*.txt;*.FMT", 1, "请选择文件", , True) '如果未选择任何文件,则退出 If Not IsArray(FileToOpenTxt) Then MsgBox "未选择任何文件!" Exit Sub End If '开始计时 Begin = Timer Application.ScreenUpdating = False Application.DisplayAlerts = False
i = 0
'逐行读取文件内容 For Files_Txt = LBound(FileToOpenTxt) To UBound(FileToOpenTxt) Open FileToOpenTxt(Files_Txt) For Input As #1 Do Until EOF(1) Line Input #1, SourceLine LineContent = SourceLine 'LineContent = Split(SourceLine, Chr(44), -1) i = i + 1 '记录读取文件的总行数 Loop Close #1 Next Over = Timer Application.ScreenUpdating = True Application.DisplayAlerts = True MsgBox ("已运行完成!FileOpenTxt共运行" & Over - Begin & "s。" & " " & i) End Sub
二、使用FileSystemObject方式读取文本文件,参考代码如下:
Sub FileSystemObjectTxtInput() Dim FileToOpenCsv Dim Begin Dim Over Dim fso_SeqCsv FileToOpenCsv = Application.GetOpenFilename("TXT文档(*.*),*.*", 1, "请选择需要导入的txt文件", , True) If Not IsArray(FileToOpenCsv) Then MsgBox "未选择任何文件!" Exit Sub End If '开始计时 Begin = Timer Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 i = 0 Application.ScreenUpdating = False Application.DisplayAlerts = False Set fso_SeqCsv = CreateObject("Scripting.FileSystemObject") For i_FilesNumCsv = LBound(FileToOpenCsv) To UBound(FileToOpenCsv) Set SeqCsvFiles = fso_SeqCsv.OpenTextFile(FileToOpenCsv(i_FilesNumCsv), ForReading, True, TristateTrue) Do While Not SeqCsvFiles.AtEndOfLine SeqAlarm_Line = SeqCsvFiles.ReadLine pmSglAlarmAll = SeqAlarm_Line 'pmSglAlarmAll = Split(SeqAlarm_Line, Chr(44), -1) i = i + 1 '记录读取文件的总行数 Loop Next Application.ScreenUpdating = True Application.DisplayAlerts = True Over = Timer MsgBox ("已运行完成!FileSystemObject共运行" & Over - Begin & "s。" & " " & i) End Sub