我正在尝试使用以下代码将数据集从excel上传到访问数据库。
但是我一直得到运行时错误3078-应用程序定义或对象定义错误。我正在使用dao,并添加了以下参考:
Microsoft office 16.0访问数据库引擎对象库, 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
请告诉我这里缺少的东西。谢谢!
答案 0 :(得分:1)
从Excel到Access。 。 。
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim blnHasFieldNames As Boolean
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = False
' Replace C:\Documents\ with the real path to the folder that
' contains the EXCEL files
strPath = "C:\Documents\"
' Replace tablename with the real name of the table into which
' the data are to be imported
strTable = "tablename"
strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
strTable, strPathFile, blnHasFieldNames
' Uncomment out the next code step if you want to delete the
' EXCEL file after it's been imported
' Kill strPathFile
strFile = Dir()
Loop
答案 1 :(得分:0)
如果路径和excel名称是固定的;您可以使用功能区中的外部功能手动执行导入 - 最后将提示将这些步骤保存为已定义的导入。
然后,您可以仅通过docmd重新运行导入以运行已保存的导入