从Excel更新Access表 - 表示当前记录已被删除?

时间:2015-10-15 08:08:15

标签: excel excel-vba ms-access access-vba sql-update vba

基本上我在这里有一些代码从Excel更新Access,它通过查看'监控ID'是否等于'IngID'(本质上是监控ID)来实现。所以基本上如果它们匹配,代码需要将更新标记为“TOWN”的访问表中的字段。

然而,当我这样做时,我在.Fields("TOWN") = Cells(lngRow, 74).Value收到错误。错误是:“运行时错误3021 BOF或EOF为True,或者当前记录已被删除。请求的操作需要当前记录。” 该记录确实存在于表中,我尝试过多次,但它似乎仍然没有用,有什么想法吗?

 Application.ScreenUpdating = False    ' Prevents screen refreshing.

Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim fld As ADODB.Field
Dim MyConn
Dim lngRow As Long
Dim lngID, LR, Upd
Dim sSQL As String

LR = Range("BN" & Rows.Count).End(xlUp).Row
Upd = LR - 1

lngRow = 1
Do While lngRow <= LR


lngID = Cells(lngRow, 66).Value


sSQL = "SELECT * FROM Tbl_Primary WHERE MonitorID = '" & lngID & "'"


Set cnn = New ADODB.Connection

MyConn = "Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source =location of access file.mdb"
With cnn

.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open MyConn

End With

Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open sSQL, ActiveConnection:=cnn, _
CursorType:=adOpenKeyset, LockType:=adLockOptimistic

'Load all records from Excel to Access.


With rst
'
.Fields("TOWN") = Cells(lngRow, 74).Value


rst.Update
End With

' Close the connection
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing

lngRow = lngRow + 1

Loop
MsgBox "Update Complete"

1 个答案:

答案 0 :(得分:0)

编辑:这不是问题。

sSQL = "SELECT * FROM Tbl_Primary WHERE MonitorID = '" & lngID & "'"

如果MonitorID是一个数字,'不属于那里,你只需要它们用于字符串 所以:

sSQL = "SELECT * FROM Tbl_Primary WHERE MonitorID = " & lngID

虽然我不确定它会解决这个问题,但不幸的是,Jet对这些错误感到宽容。