【发布时间】:2017-09-22 06:15:13
【问题描述】:
我正在尝试使用以下代码将数据集从 excel 上传到 access 数据库。
但是我不断收到运行时错误 3078 - 应用程序定义或对象定义错误。我为此使用 dao 并添加了以下参考:
Microsoft office 16.0 access 数据库引擎对象库, Microsoft 访问 16.0 库。
我无法添加 Microsoft DAO 3.6 对象库(名称与现有模块、项目或对象库冲突
代码如下:
Sub access_upload()
Dim strMyPath As String, strDBName As String, strDB As String
Dim i As Long, n As Long, lLastRow As Long, lFieldCount As Long
Dim daoDB As DAO.Database
Dim recSet As DAO.Recordset
strDBName = "Database8.accdb"
'presume to be in the same location as the host workbook:
strMyPath = ThisWorkbook.Path
strDB = strMyPath & "\" & strDBName
Set daoDB = DBEngine.Workspaces(0).OpenDatabase(strDB)
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet2")
Set recSet = daoDB.OpenRecordset("Database8")
lFieldCount = recSet.Fields.Count
lLastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To lLastRow
recSet.AddNew
For n = 0 To lFieldCount - 1
recSet.Fields(n).Value = ws.Cells(i, n + 1)
Next n
recSet.Update
Next i
recSet.Close
daoDB.Close
Set daoDB = Nothing
Set recSet = Nothing
End Sub
请让我知道我在这里缺少什么。谢谢!
【问题讨论】:
-
你在哪一行得到错误?
-
设置 recSet = daoDB.OpenRecordset("Database8") '这一行
-
你的表叫Database8吗?
-
我的访问数据库名称是Database8
-
是的,但是在您的
OpenRecordset中,您需要输入要插入数据的表名,而不是您的数据库名