我目前正在爲我的數據庫在VBA中進行搜索循環。在這個數據庫中,我有兩個表格,一個客戶記錄叫做Main
,另一個叫搜索詞叫Sparr
。這個想法是使用一個過濾器來過濾與Sparr
表中的任何搜索詞匹配的客戶。任何與任何搜索詞不匹配的客戶都會被添加到名爲filteredCustomerT
的另一個表中。訪問VBA搜索循環
例如:
table "Main"
Field "Mail"
[email protected]
[email protected]
[email protected]
[email protected]
table "Sparr"
Field "sparrord"
hotmail
jonny
table "Testtable"
Field "testMail"
[email protected]
[email protected]
所以,如果我運行此VBA代碼我想[email protected]
和[email protected]
被過濾掉。 Main
表包含200k個記錄,而Sparr
表包含2k個搜索詞。我寫了一些VBA代碼,應該循環訪問Main
表。對於Main
表中的每個記錄,都有另一個循環遍歷Sparr
表的嵌套循環,以查看是否有任何匹配。如果沒有匹配,則VBA代碼將該條目複製到名爲Testtable
的另一個表中。我使用inStr
函數來進行匹配。
下面我發佈了似乎不起作用的VBA代碼。任何人都可以幫我螞蟻指出代碼中的錯誤。我對VBA編程非常陌生。
Option Compare Database
Option Explicit
Sub filter()
Dim mainMail As Recordset
Dim sparrSokord As Recordset
Dim testtableTestmail As Recordset
Dim mainTemp As String
Dim sparrTemp As String
Dim match As Integer
Set mainMail = CurrentDb.OpenRecordset("Main")
Set sparrSokord = CurrentDb.OpenRecordset("Sparr")
Set testtableTestmail = CurrentDb.OpenRecordset("Testtable")
Do Until mainMail.EOF
mainTemp = mainMail![Mail]
match = 0
sparrSokord.MoveFirst
Do Until sparrSokord.EOF
sparrTemp = sparrSokord![sparrord]
If (InStr(mainTemp, sparrTemp) <> 0) Then
match = 1
Exit Do
End If
sparrSokord.MoveNext
Loop
If (match = 0) Then
testtableTestmail.AddNew
testtableTestmail![testMail] = mainTemp
testtableTestmail.Update
End If
mainMail.MoveNext
Loop
End Sub
謝謝你的改進建議!有沒有比Instr更好的功能來比較單詞? – codeer
不是真的......你只需要認識到空值/空字符串可能不會立即執行你的想法(設置https://msdn.microsoft.com/en-us/library/8460tsh1%28v的返回值部分= vs.90%29.aspx爲例 - 它適用於VS2008,但它可能與VBA一致) – BIBD
我已經更新了VBA代碼,現在它可以工作。唯一的問題是,只有40k的200k記錄然後崩潰。但它會刪除包含搜索詞的所有條目。 我已經更新了上面的代碼。 但它和以前沒有相同的名字。 主表被稱爲「主」,該字段被稱爲「郵件」。而serchword表被稱爲「Sparr」,其中「sparrord」作爲其領域。並且它將新條目移動到「testtable」字段「testMail」 Main - Mail Sparr - sparrord Testtable - testMail – codeer