我正在尝试将工作表导出到Access,将其粘贴到现有表中。我引用了this post,this other post,and this other post。我收到的错误在我认为可能与VBA库有关的任何一个中都没有解决,但可能是完全不同的错误。这是我的代码:
Sub ExcelToAccessAdo()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, row As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=filepath\AccessDB.accdb;" 'this is a different filepath from the real one.
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "Table Export", cn, adOpenKeyset, adLockOptimistic, adCmdTable
row = 2 ' the start row in the worksheet
Do While Not IsEmpty(Worksheets("Table Export").Range("A" & row))
With rs
.AddNew ' create a new record
.Fields("REPTNO") = Worksheets("Table Export").Range("A" & row).Value
.Update
End With
row = row + 1
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
工作表名称和Access表名称相同。 .Fields("REPTNO")
行也是直接来自其他人的帖子,所以我不知道我是否必须改变它。
错误为Run-time error '-2147217900 (80040e14)': Syntax error in FROM clause.
在rs.Open "Table Export", cn, adOpenKeyset, adLockOptimistic, adCmdTable
行。
这是一个奇怪的错误,因为它似乎是我在运行SQL时遇到的错误,但我假设有一些背景SQL发生了INSERT INTO
子句。这可能是Excel的某种类型的文件路径问题?有什么帮助吗?
以下是我的图书馆参考资料:
答案 0 :(得分:0)
感谢@JNevill指出我只需要使用方括号:
rs.Open "[Table Export]", cn, adOpenKeyset, adLockOptimistic, adCmdTable
答案 1 :(得分:0)
尽量远离任何对象名称中的空格(Tables,Field_Names,Forms,Reports等)。你可以做到这一点,但正如你所知道的那样,它会导致更多的时间和不必要的挫折感来规范事物。另外,请勿在代码中使用保留字。