编写了一个代码来检查是否已存在特殊问题,如果存在则。 代码实际上工作正常但是只要j = 1,在显示正确的记录后就会出错。所以基本上代码可以工作,但是一旦我取消选择该字段就会出现错误。 运行时错误2105 - 您无法转到指定的记录
所以我的错误是由条件引起的,然后是j = 1.但那里错了。
Private Sub txtnmb_LostFocus()
Dim i As Integer
Dim j As Integer
Dim SearchNmb As Long
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM tblNumber")
' Function to prevent to check existing records
If Me.txtOpenDate.Value <> Date And (Len(Nz(Me.txt_History_W)) <> 0 Or Len(Nz(Me.txt_Q_Desc_History)) <> 0 Or Len(Nz(Me.txt_S_History)) = False Or Len(Nz(Me.txt_P_history)) <> 0) Then
Exit Sub
End If
If Len(Nz(Me.txtnmb.Value)) <> 0 Then
SearchNmb = Me.txtnmb.Value
j = 0
' Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
' Moves to the first record and checks every record for matching the new issue
rs.MoveFirst
Do Until rs.EOF = True
If rs![Nmb] = SearchNmb Or rs![Nmb_Alternative] = SearchNmb Then
Me.Undo
i = 0
j = 1
End If
i = i + 1
rs.MoveNext
Loop
' If there is a matching record it goes there
If j = 1 Then
DoCmd.GoToRecord acDataForm, "Adding Form", acPrevious, i
End If
End If
End If
rs.Close
Set rs = Nothing
End Sub
由于
答案 0 :(得分:2)
我觉得你的代码中有很多东西要改变。首先选择你的活动。每次控制获得并失去焦点时,都会触发失去焦点。但是通过对你所写内容的理解,我认为这是你在“新纪录”中输入的数字。所以它应该检查表是否存在记录。如果确实如此,则不应添加新记录,而是将其放在那里,以便您可以继续编辑它。在这种情况下,您需要BeforeUpdate事件。
接下来是Recordset对象。您不需要遍历记录集对象。在表上执行简单的DCount之后,您可以简单地使用FindFirst方法。
Private Sub txtnmb_BeforeUpdate(Cancel As Integer)
Dim SearchNmb As Long
' Function to prevent to check existing records
If Not Me.NewRecord Then Exit Sub
If Len(Nz(Me.txtnmb)) <> 0 Then
SearchNmb = Me.txtnmb
If DCount("*", "tblNumber", "Nmb = " & SearchNmb & " OR Nmb_Alternative = " & SearchNmb) <> 0 Then
Cancel = True
With Me.Recordset
.FindFirst "Nmb = " & SearchNmb & " OR Nmb_Alternative = " & SearchNmb
End With
End If
End If
End Sub