Excel数据到Access DB - Get:操作必须使用可更新的查询错误

时间:2017-06-19 15:31:35

标签: excel excel-vba ms-access vba

我正在开发一个Excel应用程序,它允许用户通过用户表单输入工作时间,并将信息存储在Access数据库中。我是excel和访问连接的新手。我能够连接到数据库,但由于 .Update命令的运行时错误,未保存/创建记录。 运行时错误'-2147467259(80004005)':操作必须使用可更新的查询。

我搜索并搜索过,无法找到解决此问题的方法。我希望有人能够提供帮助。 (以下代码)

Sub Export_Data_Access_TI1()

Dim dbPath As String
Dim x As Long, i As Long
Dim nextrow As Long
Dim user As String
Dim NewSht As Worksheet
Dim strQuery As String
Dim recDate As String
Dim Week_Of As String

user = Sheet1.Range("A1").Text

On Error GoTo ErrHandler:

'Variables for file path and last row of data
dbPath = "H:\PROJECTS\CAI_DOT-Time Tracker\CAI_EMP_SignIn_Database.accdb"
nextrow = Cells(Rows.Count, 1).End(xlUp).Row

'Initialise the collection class variable
Set cnn = New ADODB.Connection

'Check for data
If Sheets(user).Range("A2").Value = "" Then
MsgBox " There is no data to send to MS Access"
Exit Sub
End If

cnn.Mode = adModeReadWrite
'cnn.Mode = adModeShareDenyNone
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath

Set rst = New ADODB.Recordset 'assign memory to the recordset

rst.CursorLocation = adUseClient
rst.Open Source:="DATA", ActiveConnection:=cnn, _
    CursorType:=adOpenKeyset, LockType:=adLockPessimistic, _
    Options:=adCmdTable
'rst.Supports (adAddNew)

x = 2  'the start row in the worksheet
Do While Len(Sheets(user).Range("A" & x).Formula) > 0

With rst

.AddNew 'create a new record

.Fields("Date") = ActiveWorkbook.Sheets(user).Range("A" & x).Value
.Fields("Week_Of") = Sheets(user).Range("B" & x).Value
.Fields("Month") = Sheets(user).Range("C" & x).Value
.Fields("Name") = Sheets(user).Range("D" & x).Value
.Fields("Time_In") = Sheets(user).Range("E" & x).Value
.Fields("Time_Out") = Sheets(user).Range("F" & x).Value
.Fields("Time_In2") = Sheets(user).Range("G" & x).Value
.Fields("Time_Out2") = Sheets(user).Range("H" & x).Value
.Fields("Group") = Sheets(user).Range("I" & x).Value
.Fields("UniqueID") = Sheets(user).Range("J" & x).Value
.Fields("Comments") = Sheets(user).Range("K" & x).Value

.Update 'stores the new record
End With

x = x + 1 'next row
Loop

rst.Close

cnn.Close

Set rst = Nothing
Set cnn = Nothing

'communicate with the user
MsgBox " The data has been successfully sent to the access database"

'Update the sheet
Application.ScreenUpdating = True

'Clear the data
'Sheets(user).Range("A1:K1000").ClearContents
On Error GoTo 0
Exit Sub
ErrHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"
End Sub

1 个答案:

答案 0 :(得分:0)

据我了解,DATA是远程accdb中的查询。如果是这样,它应该是可更新的。例如,请参阅:Why is my query not updateable?了解标准。如果这是一个表,请检查您是否对accdb具有读写权限,并且该文件没有只读属性。