【发布时间】:2016-12-08 12:53:06
【问题描述】:
我目前使用 Microsoft Office 2007,并将 Access 2007 数据库链接到 Excel 2007 数据库。到目前为止,一切都很好。我可以更新 Access 数据库,它会自动显示在 Excel 文件中。这就是我遇到问题的地方。
当我尝试从 Excel 中更新 Access 数据库时;我不断收到运行时 3251 错误。 =>运行时错误现已解决,但当我尝试添加数据时出现关于 NULL 值的新问题?
Sub ADODBExcelToAccess()
'Collecting data from the
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
'---NOTE: Sheet is set to auto refresh data from the database on loading---
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=" & Application.ActiveWorkbook.Path & "\linktest.accdb;"
' open a recordset (i.e. a table)
Set rs = New ADODB.Recordset
rs.Open "linktest", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
For i = 4 To 16
x = 0
Do While Len(Range("K" & i).Offset(0, x).Formula) > 0
With rs
'create a new record
.AddNew
.Fields("ID") = Range("A1" & i).Value
.Fields("PriceID") = Range("B1").Value
.Fields("ProductCode") = Range("C1").Value
.Fields("Price") = Range("D1" & i).Value
.Fields("CurrencyType") = Range("E1").Value
.Fields("Type") = Range("F1").Value
.Fields("Production") = Range("G1" & i).Value
.Fields("Quantity") = Range("H1" & i).Value
.Fields("Details") = Range("I1" & i).Value
.Fields("DateUpdated") = Range("J1" & i).Value
.Fields("Setup") = Range("K1" & i).Value
' stores the new record
.Update
End With
x = x + 1
Loop
Next i
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
我当前使用的参考库是 Active X Data Objects 2.1 Library。
【问题讨论】:
-
哪一行是错误的?更新了吗?
-
对不起,它在“.addNew”上,或者至少是突出显示的那一行错误是 3251 错误,它指出“当前记录集不支持更新。这可能是提供者的限制, 或选定的锁类型”
-
我讨厌访问数据库。但是,如果您不想使用 DAO,请尝试使用 adoopendynamic 而不是 keyset 打开。在 .open 之后检查 RS.updatable 属性,以确保您录制的内容可以更新。 ID 是主键字段吗?
-
ADO 2.1 版确实已经过时了(它似乎是在 1990 年代后期发布的)。尝试参考 2.8 版
-
您可能需要在连接字符串中添加“;Persist Security Info”... 或者您可以随时尝试 DAO
标签: vba excel ms-access-2007 excel-2007