我在内存中加载了一个csv文件。我的csv文件使用"; "作为字段定界符。
似乎vba默认的定界符是","因为当我试图访问加载的csv文件中的某一行和某一列时,vba会根据使用的","的数量在元素中前进。
例如:在我的数据中,第10行有一个","。
在我的数据的第10行有5列:aa 12,34 bb 5,678 (这里", "是小数点分隔符)
在csv文件中,分隔符是";",它看起来像这样。
aa;12,34;bb;5,678。
所以当我写
MyData(10,2)
我希望得到12,34,但vba返回34;bb;5,因为它使用", "作为字段分隔符。
所以我的问题是:如何告诉vba在加载的csv文件中使用", "来搜索?
我如何告诉vba在搜索加载的csv文件时用"; "作为定界符而不是","?
谢谢。
与其尝试改变excel在加载csv文件时使用的定界符,不如直接自己动手做。
首先,你使用一个函数将一个文本文件的行加载到一个集合中,然后你访问该集合中想要的行,并进入想要的列。
这个函数的代码
Option Explicit
Function txtfileinCol(filename As String) As Collection
' loads the content of a textfile line by line into a collection
Dim fileContent As Collection
Set fileContent = New Collection
Dim fileNo As Long
Dim txtLine As String
fileNo = FreeFile
Open filename For Input As #fileNo
Do Until EOF(fileNo)
Line Input #fileNo, txtLine
fileContent.Add txtLine
Loop
Close #fileNo
Set txtfileinCol = fileContent
End Function
Sub Testit()
Const DELIMITER = ";"
Dim filename As String
Dim col As Collection
Dim vdat As Variant
Dim colNo As Long
Dim rowNo As Long
filename = "C:\Temp\FILE.csv"
Set col = txtfileinCol(filename)
colNo = 2
rowNo = 10
vdat = col.Item(rowNo) 'here you get the line you want
vdat = Split(vdat, DELIMITER) ' now you split the line with the DELIMITER you define
Debug.Print vdat(colNo - 1) ' now you print the content of the column you want
End Sub
更新: 对于访问行和列,你也可以使用一个函数。代码是这样的
Option Explicit
Function txtfileinCol(filename As String) As Collection
' loads the content of a textfile line by line into a collection
Dim fileContent As Collection
Set fileContent = New Collection
Dim fileNo As Long
Dim txtLine As String
fileNo = FreeFile
Open filename For Input As #fileNo
Do Until EOF(fileNo)
Line Input #fileNo, txtLine
fileContent.Add txtLine
Loop
Close #fileNo
Set txtfileinCol = fileContent
End Function
Function getColRow(fileLines As Collection, rowNo As Long, colNo As Long, Optional delimiter As String) As String
Dim vdat As Variant
On Error GoTo EH:
If Len(delimiter) = 0 Then
delimiter = ";"
End If
vdat = fileLines.Item(rowNo) 'here you get the line
vdat = Split(vdat, delimiter) 'now you split the line with the delimiter
getColRow = vdat(colNo - 1) 'now you retrieve the content of the column
Exit Function
EH:
getColRow = ""
End Function
Sub Testit()
Dim filename As String
Dim col As Collection
filename = "C:\Temp\FILE.csv"
Set col = txtfileinCol(filename)
Debug.Print getColRow(col, 10, 2, ";")
End Sub