【发布时间】:2014-12-02 11:06:45
【问题描述】:
我正在开发一个 VBA 应用程序,我想在其中打开一个 CSV 文件,获取某一行的内容,并将其存储在一个字符串中。我已经让它工作了,但这似乎是一种蛮力方法,我觉得应该有一种更优雅的方式来做这件事,而不是加载每一行直到我想要的那一行。
Dim RowCount As Long
Dim CurrentLine As Long
Dim objFSO, objFile
Const ForReading = 1
RowCount = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(FileName, ForReading) 'Open specified file
CurrentLine = 0 'Start with line "0"
Message = objFile.ReadLine 'Read contents of first line
Do While CurrentLine < EventNumber 'If the current line being examined is not the specified line
CurrentLine = CurrentLine + 1 'Increment the current line counter
Message = objFile.ReadLine 'And copy the specified line to the Message string
Loop 'And repeat
objFile.Close 'Close the file when done
谁能提出更好的方法?
另外 - 如果我要加载的条目太长,我会遇到麻烦吗?需要多长时间?在 PLC 编程世界中,标准字符串是 82 个字符,这是否也适用于 VBA?
【问题讨论】:
-
不用担心字符串长度。我认为可能是 16,384,但不确定。不幸的是,CSV 文件是连续的,因此您需要阅读直到找到所需的行。如果它是一个非常大的文件,并且您大致知道该文件的位置,您可以尝试发挥创意并将其视为随机文件,但这有其自身的一系列问题。