Ошибка импорта из Excel для доступа с ADO - PullRequest
0 голосов
/ 05 октября 2018

Я пытаюсь экспортировать данные из файла Excel в файл доступа, используя vba.

Мой код:

Sub Export_Data()
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim x As Long, i As Long
Dim nextrow As Long

'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = Sheet19.Range("I3").Value
nextrow = Cells(Rows.Count, 1).End(xlUp).Row

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

'Check for data
If Sheet18.Range("A2").Value = "" Then
MsgBox " Add the data that you want to send to MS Access"
Exit Sub
End If

'Connection class is equipped with a —method— named Open
'—-4 aguments—- ConnectionString, UserID, Password, Options
'ConnectionString formula—-Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
'two primary providers used in ADO SQLOLEDB —-Microsoft.JET.OLEDB.4.0 —-Microsoft.ACE.OLEDB.12.0
'OLE stands for Object Linking and Embedding, Database

'ADO library is equipped with a class named Recordset
Set rst = New ADODB.Recordset 'assign memory to the recordset

'ConnectionString Open '—-5 aguments—-
'Source, ActiveConnection, CursorType, LockType, Options
rst.Open Source:="ARF Form Log", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable

'you now have the recordset object
'add the values to it
For x = 2 To nextrow
rst.AddNew
For i = 1 To 29
rst(Cells(1, i).Value) = Cells(x, i).Value
Next i
rst.Update
Next x

'close the recordset
rst.Close
' Close the connection
cnn.Close
'clear memory
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

'show the next ID
Sheet19.Range("h7").Value = Sheet19.Range("h8").Value + 1

'Clear the data
Sheet18.Range("A2:ac1000").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}

Где:

В листе 19 содержится мойпуть к файлу доступа

Лист 18 содержит данные, которые я хочу передать

Когда я пытаюсь перенести свои данные из листа 18 в таблицу доступа, я получаю сообщение об ошибке:

Ошибка -2147217900 (синтаксическая ошибка в предложении From.) В процедуре Export_Data

Я проверил, совпадают ли мои заголовки между файлом доступа и файлом excel, и формат данных одинаковый.

Я не уверен, где есть проблема.

Дайте мне знать ваши мысли, спасибо за внимание!

1 Ответ

0 голосов
/ 05 октября 2018

adCmdOpenTable все еще требует, чтобы имя вашей таблицы было заключено в скобки.По сути, он просто добавляет SELECT * FROM в начале вашего источника, а затем пытается выполнить его.Поскольку в имени таблицы есть пробелы, это приводит к синтаксической ошибке в предложении From.

Либо добавьте скобки, либо используйте вместо этого обычный запрос:

rst.Open Source:="SELECT * FROM [ARF Form Log]", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic
...