使用VBA将Excel中的数据插入到Access中

我已经做了一些代码插入到Excel数据库中的数据 – 我的代码如下:

Sub AddData() Dim Cn As ADODB.Connection Set Cn = New ADODB.Connection 'lets connect to the workbook first, I tested this, it works for me Cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sample.xls;Extended Properties=Excel 8.0;" _ & "Persist Security Info=False" ' Append data from Sheet1 of workbook to Table1 of mydb.mdb: Cn.Execute "INSERT INTO tblSales IN 'C:\Users\User\Documents\access.mdb' SELECT * FROM [datasheet]" Cn.Close Set Cn = Nothing End Sub 

我的问题是执行此操作时出现错误“Microsoft Jet引擎无法find对象的path”数据表“。数据表只是数据在工作簿中的工作表的名称任何帮助,非常感激。

如果您在表单名称之后放置$符号,会发生什么情况[datasheet $]?

我认为你不能在任何打开的工作簿上执行查询。 它必须针对一个文件运行,这意味着你必须提供一个完整的path给你工作表,包括文件名。 如果您的工作簿是“脏”,您需要先保存它。 我宁愿

  • 循环工作表行并逐个添加logging
  • 或者使用刚刚从Access中写入的代码(如果合适的话)

就我所知,缺less的就是数据源的path和数据表中的string:

 Data Source=sample.xls; 

应该阅读,例如:

 Data Source=c:\docs\sample.xls; 

和:

 SELECT * FROM [datasheet$] 

SELECT语句在数据库本身上运行,但是您想从EXCEL发送值。 所以你必须使用

 cn.Execute "INSERT .... VALUES (" & excelcell_or_variable & ");" 

最终在一个循环中处理所有的行/列等

希望有所帮助

祝你好运

编辑…不要忘记CHAR和interpunctations周围的引号; 我用

 ' .... ' .... "...VALUES (" & T(Q(MyStringCell)) & T(MyNumCell) & Q(MyLastTextCell) & ");" ' .... ' surrounds a string by single quotes Private Function Q(Arg as String) As String Q = "'" & Arg & "'" Return ' appens a comma to a string Private Function T(Arg as String) As String T = Arg & "," Return 

编辑2我想在EXCEL中,你想插入数据库的值都在1行…

假设你有一个包含多于一行的source_range,你必须为该范围内的每一行激发INSERT语句。 您可以使用.Rows属性从范围中返回一行。 并且通过使用.Cells(1, 1) .Cells(1,2) ….等等将多个列发送到同一行内的INSERT语句

例:

 Sub Test() Dim MyRange As Range, MyRow As Range Set MyRange = Range([B4], [C8]) ' source range For Each MyRow In MyRange.Rows ' get one row at the time from source range Debug.Print MyRow.Cells(1, 1), MyRow.Cells(1, 2) ' replace the above by your INSERT statement Next MyRow End Sub