2016-09-14 13 views
3

由於前面提供的幫助,我有一個函數方法來計算記錄集中字符串之間的字頻率。以下代碼會生成所需的結果。訪問VBA:Scripting.Dictionary - 轉儲到表?

最後一步是將字典結構轉儲到當前數據庫的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. 我可以轉儲字典到表散裝VS步進直通鑰匙一個接一個?

理由:更容易(對我來說)執行下游演示&使用表結構進行操作。

謝謝!

+1

真的是沒有辦法做到這一點沒有循環。即使在.NET中,從Dictionary中最接近的也是一組鍵/值對。 DAO連接應該通過INSERT循環提供良好的性能。 – Comintern

+0

爲什麼不直接將它添加到表中,而是先寫入字典。然後你可以將數據分組。 –

回答

1

您的代碼不顯示您如何嘗試插入行 - 我假設每行有單獨的INSERT INTO (...) VALUES (...)語句?

對於循環中的多個插入,請勿使用SQL INSERT語句。相反,使用DAO.Recordset.AddNew,它會更快。

看到這個答案:https://stackoverflow.com/a/33025620/3820271

而且這裏的一個例子:https://stackoverflow.com/a/36842264/3820271

+1

Andre,17K「.AddNew」按照您的建議插入<1秒。沒想到!謝謝(我修改了上面的代碼以反映「.AddNew」部分)。 –

+0

@MarkPelletier:您可以通過刪除'.Bookmark = .LastModified'來刪除更多的ms - 這隻有在您想要從新添加的記錄中讀取數據時才需要。一個自動編號主鍵。 – Andre