gpt4 book ai didi

vba - Excel VBA - 文本文件的导入部分(二进制导入)

转载 作者:行者123 更新时间:2023-12-04 21:00:51 24 4
gpt4 key购买 nike

第一次发帖-请温柔:)

我的工作服务器上有一个大文本文件(大约 50MB)。该文件按关键字按升序排序。我想知道是否可以使用二进制搜索搜索和导入与 key 匹配的文件部分。

例如,代码会占用文件的 512kb 并查看我需要的数据是否在文件的那部分,如果没有,则移动到下一个 512kb,直到找到我们需要的数据。此外,键将包含多行 (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

当然,这假设您的“键”在每行的第一列内。如果没有,只需根据自己的喜好进行适当的调整。

关于vba - Excel VBA - 文本文件的导入部分(二进制导入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36547257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com