2015-09-04 40 views
1

我已經構建了重複記錄的查詢。我需要運行一些VBA代碼來檢查記錄是否已經在表中(查詢)。如果是這樣,我需要刪除最後一條記錄。從查詢vba中刪除重複記錄

我的形式由帶有值的按鈕,這樣,當你點擊按鈕,數據插入到表

Dim qry As QueryDef 
Set qry = CurrentDb.QueryDefs("duplicate records") 
'which method do i use to see if the query got duplicate record' 

With rstCategories 
.MoveLast 0 
End With 
With rstCategories 
rstCategories.Delete 
End With 

MsgBox "The problem already reported before!" 

回答

1

好的我解決了它 我使用查找重複查詢嚮導創建了一個查詢。

then i insert this code in "form close" 
Dim db As DAO.Database 
Dim rs As DAO.Recordset 
Set db = Application.CurrentDb 
Set rs = db.OpenRecordset("qry_Duplicates") 


Do Until rs.EOF 
rs.MoveFirst 
rs.delete 
rs.Close 
Set rs = Nothing 
Set rs = db.OpenRecordset("qry_Duplicates") 
Loop 

這個代碼刪除整個行

1

我會做的是你的桌子上運行快速查詢:

Dim db as Database 
Dim rec as Recordset 

Set db = CurrentDB 
Set rec = db.OpenRecordset ("SELECT * FROM MyTable WHERE MyValue = '" & Me.MyValue & "'") 

If rec.EOF = true then 
    'No match found, so the value isn't in the table. Add it. 
Else 
    'Match found. This value is already in the table. 
    MsgBox "This value is already in the table" 
End If 
+0

thanx的答覆。讓我解釋一下。我在訪問2013中使用了重複記錄查詢中的構建,並在查詢中添加了一些標準,只顯示最近7天的記錄。現在如果我使用表我將不得不使用「dcount」我的查詢有5個字段,所以我只想做「暗淡」我的查詢和使用「如果」'新記錄已添加'然後刪除它 – eshai

+0

你可以編輯OpenRecordset並添加一個匹配的日期?就像「SELECT * FROM MyTable WHERE MyValue ='」&Me.MyValue&''AND MyDateField> =#「&DateAdd('d',-7,Now())&」#「 –

+0

這段代碼會很麻煩,因爲我將不得不聲明每個「文本字段爲」,並使用&和&和&相信我我有這個代碼,並有很多程序do.pls只是「打開查詢爲道」,並把「if」方法看看是否有新的記錄在查詢中「然後」移動最後刪除「我知道爲什麼我使用這種方法 – eshai