【发布时间】:2018-09-21 17:00:37
【问题描述】:
我有一个包含大约 6GB 数据的 .txt。用分号分隔的字段。
我需要根据预构建字典逐行检查其中一个字段,如果匹配,则将相应行的所有字段复制到二维数组中。
目前这是代码的相关部分(省略了声明和函数。不在此问题的范围内):
Set hbDict = dict_HB(hb) ''--this returns a dictionary from a function for comparison
Set FSO = CreateObject("scripting.filesystemobject")
Set myFile = FSO.OpenTextFile(sPath & sFilename, ForReading)
'--This counts how many matches occur between txt and dictionary to redim the array:
Do While myFile.AtEndOfStream <> True
textline = myFile.ReadLine
arrLine = Split(textline, ";")
If hbDict.exists(arrLine(3)) Then
arrLimit = arrLimit + 1
End If
Loop
Redim MyArray(1 to arrLimit, 1 to 31)
'--Loop again through the file, now actually adding to the redimmed array:
L = 1
Do While myFile.AtEndOfStream <> True
textline = myFile.ReadLine
arrLine = Split(textline, ";")
If hbDict.exists(arrLine(3)) Then
For c = 1 to 31
MyArray(L,C) = arrLine(c-1)
Next
L = L + 1
End If
Loop
myFile.Close
set FSO = nothing
'code continues...
第一个循环大约需要 19 分钟。再多一点。
已经尝试打开追加,但它崩溃了,可能是因为我正在运行 4gb 的 RAM。 一次加载整个文件的任何方式似乎都会使机器崩溃。 Open for input 不会读取整个文件,因此会丢失数据。 如果它可以处理超过 256 个条目,那么在第一个循环中使用集合来避免重新循环 txt 会很棒...... 当然,循环内的动态 redim 数组是毫无疑问的,因为它是性能杀手。
有没有比这更快的方法?
【问题讨论】:
-
我的想法是只读取文件一次。像现在一样阅读该行并将整行添加到集合中,以防条件为真。
-
使用 vb.net 代替 vba。它要快得多。
-
你好 braX,我不能使用 .NET,因为我在公司的环境中。不幸的是,excel vba 是我手头唯一的工具。
标签: vba excel dictionary multidimensional-array fso