我在Excel中构建了一个表,以便稍后(操作后)粘贴到Access表中。它适用于Windows中的复制粘贴,但我希望自动化该过程。我们谈论的是大量的列(A:AY)和大量的记录(10.000)。我已经看到它完成了ADO记录集,但只是一行一行。有批量方法吗?
`Public Sub Test()
Dim connDB As New ADODB.Connection
'Dim rng As Range
strDBName = "Kiian.mdb"
strMyPath = "d:\Work\kiian"
strDB = strMyPath & "\" & strDBName
Dim xlXML As Object
Dim adoRecordset As Object
Dim rng As Range
'this is a trick I found on the boards to easily create a recordset from range
'without a connection, but it creates an object, not a recordset
Sheets("mdb all").Activate
Set rng = Range("A1:ay3")
Set adoRecordset = CreateObject("ADODB.Recordset")
Set xlXML = CreateObject("MSXML2.DOMDocument")
xlXML.LoadXML rng.Value(xlRangeValueMSPersistXML)
adoRecordset.Open xlXML
connDB.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strDB
'delete records in the PVAnag Table:
strSQL = "INSERT INTO PVAnag SELECT * FROM adoRecordset"
'connDB.Execute CommandText:=strSQL
connDB.Execute strSQL, nr
MsgBox (nr)
'Sheets("mdb_all").Range("A1:AY3").CopyFromRecordset rstData
'close the objects
connDB.Close
'destroy the variables
Set adoRecSet = Nothing
Set connDB = Nothing
End Sub
` 所以基本上,我需要的是:从工作表和块插入到Access表中指定一个范围。任何帮助是极大的赞赏。 干杯
答案 0 :(得分:0)
一种方法(我还没有测试过)可能是在Excel项目中使用Access对象。在Access中导入Excel文件的速度非常快 DoCmd.TransferSpreadsheet 。 您可以通过引用 Microsoft Access对象XX.0 (XX.0是系统中安装的版本)来使用它。 然后,在代码中你有类似的东西:
Dim db AS Access.Application
Set db = new Access.Application
db.OpenCurrentDatabase filepath="D:\Database1.accdb", Exclusive:=True
db.DoCmd.TransferSpreadsheet 'all_params_here
db.CloseCurrentDatabase
db.Quit acQuitSaveAll
的详细信息
答案 1 :(得分:0)
在尝试使用TransferSpreadsheet几个小时后,我发现了另一个论坛的线索,我想出了这个:
Public Sub a()
Sheets("mdb all").Select
Range("a1:ay3").Select
Selection.Copy
strDBName = "Kiian.mdb"
strMyPath = "d:\Work\kiian"
strDB = strMyPath & "\" & strDBName
Set appAccess = CreateObject("Access.Application")
' Open database in Microsoft Access window.
appAccess.OpenCurrentDatabase strDB
appAccess.Visible = True
appAccess.DoCmd.OpenTable "PVAnag", acViewNormal, acEdit
appAccess.DoCmd.RunCommand acCmdPasteAppend
appAccess.CloseCurrentDatabase
appAccess.Quit acQuitSaveAll
End Sub
此方法使用剪贴板,只需从Excel复制,打开Access和粘贴(special = append)。无论出于何种原因,我都无法让TransferSpreadsheet工作。但是感谢您提供的输入以及让我放弃使用SQL的想法。