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

 

posted on 2013-12-08 22:30  鱼东鱼  阅读(2350)  评论(0编辑  收藏  举报

导航