VBA ado 把CSV文件当做数据源进行 查询操作

Sub F_Sample006()
    'Microsoft ActiveX Data Objects 2.X Library
    'F_Data.csv
    Dim myCon      As New ADODB.Connection
    Dim myRst      As New ADODB.Recordset
    Dim myCnc      As String
    Dim myCmd      As String
    Dim myFileName As String
    Dim i          As Long
    myFileName = "F_Data.csv"
    
    myCnc = "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
    "DBQ=" & ThisWorkbook.Path & "\;"
    
    myCmd = "SELECT * FROM " & myFileName
    
    myCon.Open "Provider=MSDASQL;" & myCnc
    
    myRst.Open Source:=myCmd, ActiveConnection:=myCon
    
    Worksheets.Add
    
    With myRst
    
        For i = 1 To .Fields.Count
            Cells(1, i).Value = .Fields(i - 1).Name
        Next
      
        Range("A2").CopyFromRecordset myRst
         ActiveSheet.Cells.Font.Name = "宋体"
        .Close
    End With
    
    myCon.Close
    Set myRst = Nothing
    Set myCon = Nothing
End Sub

 

转载于:https://www.cnblogs.com/yuzhengdong/p/3464375.html

你可能感兴趣的:(数据库)