return csv file as recordset

前端 未结 1 1331
不知归路
不知归路 2020-12-01 22:15

I have an external program that exports data into CSV files. My users would like to have access to this data through a VBA function in excel. In order to do this, I thought

相关标签:
1条回答
  • 2020-12-01 22:42

    Solved it with some tweaks of my own along with input from Tim Williams. Here is the code for anyone else who might need help

    Public Function getData(fileName As String) As ADODB.Recordset
    
        Dim path As String
        path = "C:\testDir\"
        Dim cN As ADODB.Connection
        Dim RS As ADODB.Recordset
        Set cN = new ADODB.Connection
        Set RS = new ADODB.Recordset
        cN.Open ("Provider=Microsoft.Jet.OLEDB.4.0;" & _
                       "Data Source=" & path & ";" & _
                       "Extended Properties=""text; HDR=Yes; FMT=Delimited; IMEX=1;""")
        RS.ActiveConnection = cN
        RS.Source = "select * from " & fileName
        Set getData = RS
    
    End Function
    

    Now, the function can be called as

    Dim a As ADODB.Recordset
    Set a = getData("testFile.csv")
    a.Open
    MsgBox(a.GetString())
    a.Close
    
    0 讨论(0)
提交回复
热议问题