1

尝试在 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
4

2 回答 2

0

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

"WHERE Cusip = 16163HAE1 " & _

应替换为:

"WHERE Cusip = '16163HAE1' " & _

在 SQL 中,您将字符串或文本用'(撇号)括起来。

于 2014-08-20T09:17:15.450 回答
0

Whomever is executing the function must have write access to the directory because ms-access is going to try to create a lock (ldb) file.

于 2012-07-16T13:31:47.560 回答