在Excel / Access中使用ADO连接“打开”方法错误

时间:2012-07-16 13:24:53

标签: vba ado

尝试使用VBA中的ADO连接打开数据库时出现错误 - 我收到以下错误:

运行时错误'-2147467259(80004005)': 对象'_Recordset'的方法'打开'失败

我已经检查了所有文件路径和语法的重新检查,但无法找到下面的代码有什么问题 - 有人可以帮忙吗?

Public Sub PlainTextQuery()

Dim rsData As ADODB.Recordset
Dim sConnect As String
Dim sSQL As String

Dim sCusip As String

sCusip = Trim(Range("cusip").Value)

' Create the connection string
sConnect = "Provider=Microsoft.ACE.OLEDB.12.0; " & _
    "Data Source=C:\Users\intern\Documents\NewStuff\ResiOffers_v1.accdb;"

' Create the SQL statement
sSQL = "SELECT Date, Cusip, Bond, OF, CF, Dealer, Price, Matcher, DayCount, MktValue " & _
    "FROM ResiOffersColor " & _
    "WHERE Cusip = 16163HAE1 " & _
    "ORDER BY Date;"

' Create the recordset object and run the query
Set rsData = New ADODB.Recordset
rsData.Open sSQL, sConnect, adOpenForwardOnly, _
    adLockReadOnly, adCmdText

' Make sure we get records back
If Not rsData.EOF Then
    ' Dump the contents onto the worksheet
    Sheet2.Range("A2").CopyFromRecordset rsData
    ' Close the recordset object
    rsData.Close
Else
    ' Close the recordset object
    rsData.Close
    MsgBox "Error: No records returned.", vbCritical
End If

' Destroy the recordset object
Set rsData = Nothing

End Sub

2 个答案:

答案 0 :(得分:0)

执行该函数的任何人都必须具有对该目录的写访问权,因为ms-access将尝试创建一个lock(ldb)文件。

答案 1 :(得分:0)

这里的问题是sSQL声明 这一行:

"WHERE Cusip = 16163HAE1 " & _

应替换为:

"WHERE Cusip = '16163HAE1' " & _

在SQL中,您使用'(撇号)附加了字符串或文本。