逻辑:
- 用户.按下按钮;
- 代码.创建一个记录集"rstStud"(学生)和rstGroupStud"(学生组);
- 代码.循环.枚举rstStud";
- 代码.添加条目到rstGroupStud";
- 代码.如果该记录存在,则转到循环中的下一条记录;
- 代码.如果条目是新条目,则在rstGroupStud"中添加条目;本质:一键点击 - 添加一个独特的条目.
问题.当循环过去!StudentName = "Student Name 2" 在.Update"行中出现错误.错误:"由于重复值导致更改失败索引、主键或关系.一改数据或包含重复值的多个字段删除索引或通过允许覆盖它重复值并重试.
换句话说,错误处理程序第一次正常工作,当我重新触发时,我得到一个错误.
In other words, the first time the error handler works normally, and when I re-fire, I get an error.
问题.如何让代码按照描述的逻辑运行?
Question. How to make the code work according to the described logic?
Private Sub btnAddRecord_Click() Dim nameStud As String Dim rstStud As DAO.Recordset ' Dim rstGroupStud As DAO.Recordset ' Set rstStud = CurrentDb.OpenRecordset("tbl_02_Students", dbOpenSnapshot) ' Set rstGroupStud = CurrentDb.OpenRecordset("tbl_03_GruopsStudents", dbOpenDynaset) ' ' *** rstStud With rstStud Do Until .EOF = True nameStud = !nameStud On Error GoTo errend ' *** rstGroupStud With rstGroupStud .AddNew !idGroup = Me.id_GroupFrm !nameStud = nameStud ' nameStud .Update End With rstGroupStud.Close Me.frm_03_GruopsStudents_tbl.Requery Exit Sub errend: .MoveNext Loop End With On Error Resume Next rstStud.Close Set rstStud = Nothing End Sub更新_1文件 - 链接
推荐答案你需要解开执行路径;正常和错误执行状态是交织在一起的,这就是为什么不能处理超出第一个错误的任何错误.
You need to de-tangle the execution paths; normal and error execution states are intertwined, that's why any error beyond the first one can't be handled.
Private Sub btnAddRecord_Click() Dim nameStud As String Dim rstStud As DAO.Recordset ' Dim rstGroupStud As DAO.Recordset ' Set rstStud = CurrentDb.OpenRecordset("tbl_02_Students", dbOpenSnapshot) ' Set rstGroupStud = CurrentDb.OpenRecordset("tbl_03_GruopsStudents", dbOpenDynaset) ' ' *** rstStud With rstStud Do Until .EOF = True On Error GoTo ErrHandler nameStud = !nameStud ' *** rstGroupStud With rstGroupStud .AddNew !idGroup = Me.id_GroupFrm !nameStud = nameStud ' nameStud .Update End With rstGroupStud.Close Me.frm_03_GruopsStudents_tbl.Requery Exit Do TryNext: On Error Resume Next .MoveNext If Err.Number <> 0 Then Exit Do On Error GoTo 0 Loop End With On Error Resume Next rstStud.Close Set rstStud = Nothing On Error GoTo 0 Exit Sub ErrHandler: Resume TryNext End Sub那样 ErrHandler 只会在错误状态下运行;TryNext 在happy path"中运行,Exit Do 跳出循环(但不跳出程序),这样无论结果如何,清理代码都可以运行.
That way ErrHandler only ever runs in an error state; TryNext runs in the "happy path", and Exit Do breaks out of the loop (but not out of the procedure) so that the cleanup code can run whatever the outcome is.
更多推荐
当错误再次出现时错误处理不起作用
发布评论