当错误再次出现时错误处理不起作用

编程入门 行业动态 更新时间:2024-10-09 19:17:01
本文介绍了当错误再次出现时错误处理不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

逻辑:

  • 用户.按下按钮;
  • 代码.创建一个记录集"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.

更多推荐

当错误再次出现时错误处理不起作用

本文发布于:2023-10-27 23:53:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534896.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   现时   不起作用

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!