How to query UTF-8 encoded CSV-files with VBA in Excel 2010?

前端 未结 2 562
忘掉有多难
忘掉有多难 2020-12-11 21:32

I would like to query an UTF-8 encoded CSV file using VBA in Excel 2010 with the following database connection:

provider=Microsoft.Jet.OLEDB.4.0;;data source         


        
2条回答
  •  囚心锁ツ
    2020-12-11 22:23

    The only solution for this problem I found is to use Schema.ini file.

    my test csv file

    Col_A;Col_B;Col_C
    Some text example;123456789;3,14
    

    Schema.ini for my test csv file

    [UTF-8_Csv_With_BOM.csv] 
    Format=Delimited(;)
    Col1=Col_A Text
    Col2=Col_B Long
    Col3=Col_C Double
    

    This Schema.ini file contains the name of the source csv file and describes my columns. Each column is specified by its name and type but you can specify more informations. This file must be located in the same folder as your csv file. More info here.

    Finally the VBA code which reads the csv file. Note that HDR=No. This is because the columns headers are defined in the Schema.ini.

    ' Add reference to Microsoft ActiveX Data Objects 6.1 Library
    Sub ReadCsv()
    
        Const filePath As String = "c:\Temp\StackOverflow\"
        Const fileName As String = "UTF-8_Csv_With_BOM.csv"
        Dim conn As ADODB.Connection
        Dim rs As New ADODB.Recordset
    
        Set conn = New ADODB.Connection
        conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & filePath & _
            "';Extended Properties='text;HDR=No;FMT=Delimited()';"
    
        With rs
            .ActiveConnection = conn
            .Open "SELECT * FROM [" & fileName & "]"
            If Not .BOF And Not .EOF Then
                While (Not .EOF)
                    Debug.Print rs.Fields("Col_A") & " " & _
                                rs.Fields("Col_B") & " " & _
                                rs.Fields("Col_C")
                    .MoveNext
                Wend
            End If
            .Close
        End With
    
        conn.Close
        Set conn = Nothing
    
    End Sub
    

    Output

    Some text example 123456789 3,14
    

提交回复
热议问题