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

前端 未结 2 625
忘掉有多难
忘掉有多难 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:09

    The following procedure extracts the entire CSVfile into a new Sheet, clearing the BOM from the Header. It has the Path, Filename and BOM string as variables to provide flexibility.

    Use this procedure to call the Query procedure

    Sub Qry_Csv_Utf8()
    Const kFile As String = "UTF8 .csv"
    Const kPath As String = "D:\StackOverFlow\Temp\"
    Const kBOM As String = "\xEF\xBB\xBF"
        Call Ado_Qry_Csv(kPath, kFile, kBOM)
    End Sub
    

    This is the Query procedure

    Sub Ado_Qry_Csv(sPath As String, sFile As String, sBOM As String)
    Dim Wsh As Worksheet
    Dim AdoConnect As ADODB.Connection
    Dim AdoRcrdSet As ADODB.Recordset
    Dim i As Integer
    
        Rem Add New Sheet - Select option required
        'With ThisWorkbook           'Use this if procedure is resident in workbook receiving csv data
        'With Workbooks(WbkName)     'Use this if procedure is not in workbook receiving csv data
        With ActiveWorkbook         'I used this for testing purposes
            Set Wsh = .Sheets.Add(After:=.Sheets(.Sheets.Count))
            'Wsh.Name = NewSheetName        'rename new Sheet
        End With
    
        Set AdoConnect = New ADODB.Connection
        AdoConnect.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=" & sPath & ";" & _
            "Extended Properties='text;HDR=Yes;FMT=Delimited(,);CharacterSet=65001'"
    
        Set AdoRcrdSet = New ADODB.Recordset
        AdoRcrdSet.Open Source:="SELECT * FROM [" & sFile & "]", _
            ActiveConnection:=AdoConnect, _
            CursorType:=adOpenDynamic, _
            LockType:=adLockReadOnly, _
            Options:=adCmdText
    
        Rem Enter Csv Records in Worksheet
        For i = 0 To -1 + AdoRcrdSet.Fields.Count
            Wsh.Cells(1, 1 + i).Value = _
                WorksheetFunction.Substitute(AdoRcrdSet.Fields(i).Name, sBOM, "")
        Next
        Wsh.Cells(2, 1).CopyFromRecordset AdoRcrdSet
    
    End Sub
    

提交回复
热议问题