更改加载的 csv 文件中的分隔符

Changing delimiter in a loaded csv file

我已经在内存中加载了一个csv文件。我的 csv 文件使用“;”作为字段分隔符。

似乎 vba 默认分隔符是“,”,因为当我尝试访问加载的 csv 文件的特定行和列时,vba 会参考“, “ 用过的。

示例:

在我的数据的第10行有五列:aa 12,34 bb 5,678(这里“,”是小数点分隔符)

在分隔符为“;”的csv文件中它看起来像这样:

aa;12,34;bb;5,678

所以当我写

MyData(10,2) 

我期望得到 12,34 但 vba returns 34;bb;5 因为它使用“,”作为字段分隔符。

所以我的问题是:

如何告诉 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