从excel导出数据到access-VBA

我想使用下面的代码将数据集从excel上传到访问数据库。

但是我不断收到运行时错误3078-应用程序定义或对象定义的错误。 我正在使用道,为此添加了以下参考:

微软Office 16.0访问数据库引擎对象库,微软访问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 

请让我知道我在这里失踪。 谢谢!

从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 

如果path和excel名称是固定的, 您可以使用function区中的“外部”function手动执行导入操作 – 结束时会提示将这些步骤保存为定义的导入。

然后你可以重新运行导入,只需要一个docmd来运行保存的导入