Изменение разделителя в загруженном CSV-файле - PullRequest
0 голосов
/ 29 апреля 2020

Я загрузил CSV-файл в память. Мой CSV-файл использует ";" как разделитель полей.

Кажется, по умолчанию в качестве разделителя vba используется ",", потому что когда я пытаюсь получить доступ к определенной строке и столбцу загруженного файла CSV, vba перемещается по элементам с указанием количества используемых символов ",".

пример:

В десятой строке моих данных есть пять столбцов: aa 12,34 bb 5 678 (здесь "," - десятичный разделитель)

в csv файл с разделителем ";" это выглядит так:

aa; 12,34; bb; 5678

, поэтому, когда я пишу

MyData(10,2) 

, я ожидаю получить 12,34, но vba возвращается 34; bb; 5 потому что он использует "," в качестве разделителя полей.

Итак, мой вопрос:

Как я могу сказать vba искать в загруженном файле csv по отношению к ";" в качестве разделителя вместо ","?

Спасибо.

1 Ответ

2 голосов
/ 29 апреля 2020

Вместо того, чтобы пытаться изменить разделитель, который Excel использует для загрузки файла CSV, может быть проще сделать это самостоятельно

Сначала вы используете функцию для загрузки строк текстового файла в коллекции, а затем вы получаете доступ к требуемой строке в этой коллекции и go к нужному столбцу.

Код для этого

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...