2017-02-19 153 views
0

当用户输入新记录时,我有以下检测重复产品名称。如何解决vba运行时错误3420

Private Sub ProdName_BeforeUpdate(Cancel As Integer) 

Dim Product As String 
Dim stLinkCriteria As String 
Dim rsc As DAO.Recordset 

Set rsc = Me.RecordsetClone 

Product = Me.ProdName.value 
stLinkCriteria = "[ProdName]=" & "'" & Product & "'" 

    If DCount("ProdName", "ProdProduct", stLinkCriteria) > 0 Then 
     Me.Undo 
     MsgBox "Warning duplicate entry " _ 
     & Product & " has already been entered." _ 
     & vbCr & vbCr & "You will now be taken to the record.", vbInformation _ 
     , "Duplicate Information" 
     'Go to record of original product name 
     rsc.FindFirst stLinkCriteria 
     Me.Bookmark = rsc.Bookmark 
    End If 

Set rsc = Nothing 
End Sub 

代码检查,发现重复之后却显示以下错误和不走的原单记录:

运行时错误“3420” 对象无效或不再设置

请有人帮我解决问题吗?

回答

0

尽量避免撤消(或将其移动到结束),并做取消更新:

If DCount("ProdName", "ProdProduct", stLinkCriteria) > 0 Then 
    Cancel = True 
    MsgBox "Warning duplicate entry " _ 
    & Product & " has already been entered." _ 
    & vbCr & vbCr & "You will now be taken to the record.", vbInformation _ 
    , "Duplicate Information" 
    'Go to record of original product name 
    rsc.FindFirst stLinkCriteria 
    Me.Bookmark = rsc.Bookmark 
End If 

你甚至可以跳过DCOUNT并且必须使用文本属性:

Product = Me!ProdName.Text 
stLinkCriteria = "[ProdName]=" & "'" & Product & "'" 

rsc.FindFirst stLinkCriteria 
Cancel = Not rsc.NoMatch 

If Cancel = True Then 
    MsgBox "Warning duplicate entry " _ 
    & Product & " has already been entered." _ 
    & vbCr & vbCr & "You will now be taken to the record.", vbInformation _ 
    , "Duplicate Information" 
    'Go to record of original product name 
    Me.Bookmark = rsc.Bookmark 
End If 
+0

不,它不会做魔术。试了两次,仍然出现错误。 – ezybusy

+0

那么可能'Product = Me!ProdName.Value'没有任何价值。尝试“文本” - 请参阅编辑。 – Gustav

+0

不行不行。也许我应该尝试以另一种方式应用相同的逻辑。我所需要的是在表单级别输入数据时防止重复。 – ezybusy

相关问题