【问题标题】:Exporting data from excel to access-VBA将数据从excel导出到access-VBA
【发布时间】: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 中,您需要输入要插入数据的表名,而不是您的数据库名

标签: vba excel ms-access


【解决方案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

【讨论】:

    【解决方案2】:

    如果路径和 excel 名称是固定的;您可以使用功能区中的外部功能手动逐步完成导入 - 最后将提示您将这些步骤保存为定义的导入。

    然后您可以通过 docmd 重新运行导入以运行保存的导入

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      相关资源
      最近更新 更多