访问VBA:Scripting.Dictionary - 转储到表?

时间:2016-09-14 13:28:07

标签: vba access-vba

感谢前面提供的有用的手,我有一个功能方法来计算记录集中字符串之间的字频率。以下代码生成所需的结果。

最后一步是将字典结构转储到currentDB中的Access表中。我可以通过下面的注释逐步执行每个键,并通过SQL附加到一个表 - 但它是非常慢的24K术语。

更新>> w /解决方案<<

Private Sub Command0_Click()

Dim counts As New Scripting.Dictionary
Dim word As Variant
Dim desc As String

Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset  '<< solution
Dim strSQL As String
Dim db As Database

Set db = CurrentDb

strSQL = "SELECT DISTINCT Items.Description FROM Items ;"

Set rs1 = db.OpenRecordset(strSQL, dbOpenDynaset)

Do While Not rs1.EOF
    For Each word In Split(rs1!Description, " ")
        If Not counts.Exists(word) Then
            counts.Add word, 1
        Else
            counts.Item(word) = counts.Item(word) + 1
        End If
    Next
    rs1.MoveNext
Loop

'>> .AddNew Solution inserted as suggested below <<

rs2 = db.OpenRecordset("Freq", dbOpenTable)  

For Each word In counts.Keys
    With rs2
       .AddNew             ' Add new record
       .Fields!Term = word
       .Fields!Freq = counts(word)
       .Update
       .Bookmark = .LastModified
    End With
Next

rs2.Close

'>> End Solution <<

Set rs1 = Nothing
Set rs2 = Nothing

MsgBox "Done"

End Sub

问题:

  1. 我可以将字典转储到BULK中的表格中,而不是逐步踩过密钥吗?
  2. 理由:更容易(对我来说)执行下游演示&amp;使用表结构进行操作。

    谢谢!

1 个答案:

答案 0 :(得分:1)

您的代码没有显示您是如何尝试插入行的 - 我假设每行都有单独的INSERT INTO (...) VALUES (...)语句?

对于循环中的多个插入,不要使用SQL INSERT语句。而是使用DAO.Recordset.AddNew,它会更快。

请参阅此答案:https://stackoverflow.com/a/33025620/3820271

这里举个例子:https://stackoverflow.com/a/36842264/3820271