在VBA中读取大文本文件中的前几个字符

我正在尝试读取excel中大(> 15MB)文件中的前几个字符。 现在,我正在使用典型的:

Set MyObject = New Scripting.FileSystemObject Set mySource = MyObject.GetFolder(mySourcePath) For Each myFile In mySource.Files With New Scripting.FileSystemObject With .OpenTextFile(myFile, ForReading) test_str = .ReadLine 'Do things End With End With Next 

问题是与大文件,我(相信)你加载到内存的全部东西只读取前几个字符。 有没有办法只提取前6个字符?

FileSystemObject的替代方法是ADO

但是,你的陈述

我(相信)你只是为了读取前几个字符而加载到内存中。

是错的。

我认为误导你的是你在阅读第一行后没有退出循环。 通过逐行阅读,您可以获得所需的内容,但是您没有马上closures文件。 总是closures您在代码中启动的任何对象,这是一个很好的程序员练习。 不要把它挂起来,不要依靠环境来杀死它们。

考虑下面的代码作为你的替代scheme,看看是否有任何效率差异

 Option Explicit ' add references to Microsoft Scripting Runtime ' Tools >> References >> Microsoft Scripting Runtime Sub Main() Dim fileName As String ' make sure to update your path fileName = "C:\Users\FoohBooh\Desktop\Project.txt" ReadTxtFile fileName End Sub Sub ReadTxtFile(fileName) Dim oFSO As New FileSystemObject Dim oFS As TextStream Set oFS = oFSO.OpenTextFile(fileName) Dim content As String content = oFS.ReadLine With Sheets(1).Range("A1") .ClearContents .NumberFormat = "@" .Value = content End With oFS.Close Set oFS = Nothing End Sub 

上面的代码将第一个.txt文件的第一行读取到第一个工作表的单元格A1中。 请记住将fileNamevariables设置为完整path。