VBA快速将多条记录插入到访问DB中

时间:2012-10-17 08:57:26

标签: sql vba ms-access excel-vba excel

好的,我有一个能够产生相当大量记录的电子表格(~3500)

我有以下脚本将它们插入到我的访问数据库中:

Sub putinDB()
Dim Cn As ADODB.Connection, Rs As ADODB.Recordset
Dim MyConn, sSQL As String

Dim Rw As Long, c As Long
Dim MyField, Result
Dim x As Integer
Dim accName As String, AccNum As String, sector As String, holding As String,  holdingvalue As Double, holdingdate As Date
theend = lastRow("Holdings", 1) - 1
'Set source
MyConn = "S:\Docs\Harry\Engine Client\Engine3.accdb"
'Create query
Set r = Sheets("Holdings").Range("a2")
x = 0
Do
Application.StatusBar = "Inserting record " & x + 1 & " of " & theend
accName = r.Offset(x, 0)
AccNum = r.Offset(x, 4)
sector = r.Offset(x, 2)
holding = r.Offset(x, 1)
holdingvalue = r.Offset(x, 3)
holdingdate = r.Offset(x, 5)

sSQL = "INSERT INTO Holdings (AccName, AccNum, Sector, Holding, HoldingValue, HoldingDate)"
sSQL = sSQL & " VALUES ('" & Replace(accName, "'", "''") & "', '" & AccNum & "', '" & sector & "', '" & Replace(holding, "'", "''") & "', '" & holdingvalue & "', #" & holdingdate & "#)"
Debug.Print (sSQL)
 'Create RecordSet
Set Cn = New ADODB.Connection
With Cn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .CursorLocation = adUseClient
    .Open MyConn
    Set Rs = .Execute(sSQL)
End With
x = x + 1
Loop While r.Offset(x, 0) <> "" Or x < 15
Application.StatusBar = False
End Sub

问题是,它是逐个循环遍历每个记录,每次都重建并执行查询导致执行速度非常慢(我的PC上每秒大约2-3条记录)

有没有办法让vba一次性将整个范围插入数据库而无需循环? 感谢

2 个答案:

答案 0 :(得分:5)

您提供的答案应略微改进,因为您只需要打开一次连接,但代码仍然效率低下。您真的只想用所有数据写入您的记录集,而不是像这样。我总是喜欢从Access端工作从Excel中提取信息,而不是从Excel推入Access,但我相信我们可以使用这种情况。

在这种情况下,最好使用DAO而不是ADO并使用 Transacation ,基本上你仍然遍历记录集,但是直到你提交才会发生写入数据的实际行为最后,所以速度要快得多。

这是Access方面的一个非常基本的例子:

Private Sub TestTrans()

Dim wksp    As DAO.Workspace
Dim rs      As DAO.Recordset

    Set wksp = DBEngine.Workspaces(0) 'The current database

    wksp.BeginTrans 'Start the transaction buffer

    Set rs = CurrentDb.OpenRecordset("Table1", dbOpenDynaset)

    Do 'Begin your loop here

    With rs
        .AddNew
            !Field = "Sample Data"
        .Update
    End With

    Loop 'End it here

    wksp.CommitTrans 'Commit the transaction to dataset

End Sub

答案 1 :(得分:3)

好吧,傻,我。经过一段时间的修补后,结果是

Set Cn = New ADODB.Connection
With Cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.CursorLocation = adUseClient
.Open MyConn
End With
循环外的

位使得它更快。