我有一个将数据导出到CSV文件的外部程序。我的用户希望通过excel中的VBA函数访问这些数据。为了做到这一点,我考虑将CSV文件读取包装到一个返回ADODB.Recordset的函数中。我的代码是
Public Function getData(fileName As String) As ADODB.Recordset
Dim path As String
path = "C:\testDir\"
Dim cN As New ADODB.Connection
Dim RS As 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
我正在尝试使用
调用此函数Dim a As ADODB.Recordset
Set a = getData("testFile.csv")
a.Open()
此时,我收到编译错误,说'='预期。有人能指出我应该如何调用我的函数并循环访问数据吗?
答案 0 :(得分:8)
通过我自己的一些调整和蒂姆威廉姆斯的输入解决了这个问题。以下是可能需要帮助的其他人的代码
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
现在,该函数可以被称为
Dim a As ADODB.Recordset
Set a = getData("testFile.csv")
a.Open
MsgBox(a.GetString())
a.Close