我编写了一些代码以将excel表中的数据插入到Access数据库中-我的代码如下:
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 Engine无法找到对象”数据表“的路径。数据表只是数据在我的工作簿中位于工作表的名称。非常感谢您的帮助。
如果在工作表名称后加$符号会发生什么像这样[datasheet $]?
我认为您不能仅对任何打开的工作簿执行查询。它必须针对文件运行,这意味着您必须提供工作表的完整路径,包括文件名。如果您的工作簿是“脏”的,则需要先保存它。我宁愿
据我所知,所缺少的只是数据源的路径和数据表上的字符串:
Data Source=sample.xls;
例如,应阅读:
Data Source=c:\docs\sample.xls;
和:
SELECT * FROM [datasheet$]
xlFilepath = Application.ThisWorkbook.FullName
Sql = "INSERT INTO tblSales " & _
"SELECT * FROM [Excel 12.0 Macro;HDR=YES;DATABASE=" & xlFilepath & "].[datasheet$A1:AK10011] "
cnn.Execute Sql
在数据表中的警告表前8行。假设有一个标题(HDR =是)接下来的6行应包含一个虚拟数据,以定义与访问表列定义等效的列。
SELECT语句在数据库本身上运行,但是您要从EXCEL发送值。所以你必须使用
cn.Execute "INSERT .... VALUES (" & excelcell_or_variable & ");"
最终循环处理所有行/列等。>
希望有所帮助
祝你好运
编辑...不要忘记在CHAR和标点符号周围加上引号;我用
' .... ' .... "...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包含多于1行,则必须为该范围内的每一行触发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