Excel VBA – 导入文本文件(二进制导入)

第一次发布 – 请温柔:)

我有一个大的文本文件(大约50MB),位于我们的工作服务器上。 该文件按升序sorting。 我想知道是否有可能search和导入与二进制search匹配的文件的部分。

例如,代码将占用512kb的文件,看看我需要的数据是否在文件的那一部分,如果不是,移动到下一个512kb,直到find我们需要的数据。 另外,密钥会有几行(2K)的数据,所以代码将需要查找密钥的开始和结束点。

我希望通过只加载用户需要的数据文件的部分加载文件时,节省时间。 有一个新的文件每小时产生的最新数据,由于服务器速度慢(尤其是连接远程(即在家工作)时,目前需要很长时间才能将整个文件加载到报告中。

有谁知道这是可能的吗?

非常感谢

不,不可能只加载你感兴趣的那部分文件,这主要是由于你不知道从哪里开始查看文件。 你想写什么? 开始寻找12MB位置附近的50MB文件?

但是,您可以逐行读取文件,而无需首先将整个文件加载到内存中:

Public Sub ImportToExcel() Dim intCounter As Long Dim intPointer As Integer Dim strFileToImport As String 'The location of the file you wish to load strFileToImport = "C:\tmp\test.csv" intPointer = FreeFile() Open strFileToImport For Input Access Read Lock Read As #intPointer intCounter = 1 Do Until EOF(intPointer) 'Loading row by row from the text file into strLine Line Input #intPointer, strLine 'Check if the "KeyYouAreLookingFor" can be found in that line '... if it can be found then copy it to the first sheet If InStr(1, strLine, "KeyYouAreLookingFor") Then Worksheets(1).Cells(intCounter + 1, 1).Value2 = strLine intCounter = intCounter + 1 Else 'If the key cannot be found but has been found in the past '... then (following your logic that the file is sorted) '... all other rows in the file can be ignored and '... the import is complete: so the program should stop If intCounter > 1 Then Exit Sub End If Loop Close intPointer End Sub 

查看代码中的注释以获得更多解释,并让我知道这是否适合您的需求。

假设您的50MB文本文件是一个分隔的CSV文件,您可以进一步细化上述代码,如下所示:

 If InStr(1, Split(strLine, ",")(0), "KeyYouAreLookingFor") Then 

当然,这假设你的“钥匙”在每一行的第一列内。 如果没有,只要适当调整你的喜好。