我可以使用哪种函数来搜索vba文件中的行,然后将此文件存储到数组中。 例如:
job,boe,sig,dive,mag,num,
blah,blah,,,,,
wuttt,ais,,sidji,,,
查找第一列中包含“blah”的行并将其存储到数组中。
目前我正在使用bash nawk命令查找csv文件中的行,然后将其放入文本文件中。然后我用:
Open "C:\file2.csv" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, ",")
将行存储在数组中。为了提高效率,我想取消bash部分并使用VBA直接从csv文件中读取行。
答案 0 :(得分:2)
在VBA中,有两种标准选项可用于读取文件。
这两种方法都有其优点和缺点。内置命令支持二进制文件,但API很奇怪,基于很旧版本的BASIC。 FileSystemObject有一个更现代的API,但只支持文本文件。
使用方法1的示例:
Function FindEntry(file_path As String, _
field_index As Long, field_value As String) As Variant
Dim file_number As Integer
Dim raw_line As String
Dim csv_line As Variant
file_number = FreeFile
Open file_path For Input As #file_number
Do Until EOF(file_number)
Line Input #file_number, raw_line
csv_line = ProcessCsvData(raw_line)
If UBound(csv_line) < field_index Then
' Guard against index out of bounds
ElseIf csv_line(field_index) = field_value Then
FindEntry = csv_line
Exit Do
End If
Loop
Close #file_number
End Function
使用方法2的示例:
Function FindEntry(file_path As String, _
field_index As Long, field_value As String) As Variant
' use the type Scripting.FileSystemObject if you include a reference
' to "Microsoft Scripting Runtime"
Dim fs As Object
Dim txt_file As Object
Dim csv_line As Variant
Set fs = CreateObject("Scripting.FileSystemObject")
Set txt_file = fs.OpenTextFile(file_path)
Do Until txt_file.AtEndOfStream
csv_line = ProcessCsvData(txt_file.ReadLine)
If UBound(csv_line) < field_index Then
' Guard against index out of bounds
ElseIf csv_line(field_index) = field_value Then
FindEntry = csv_line
Exit Do
End If
Loop
txt_file.Close
End Function
这两种方法都使用名为“ProcessCsvData”的函数,这是一个需要编写的函数,它将CSV行拆分为字段。这个函数的一个非常天真的实现就是这样。
' Warning: This code is wrong!
Function ProcessCsvData(csv_line As String) As Variant
ProcessCsvData = Split(csv_line, ",")
End Function
当然,这并未考虑包含逗号的字段,这些字段通常通过将字段用大多数CSV格式的引号括起来进行标记。