【问题标题】:access vba: go to next iteration on error访问vba:出错时进入下一次迭代
【发布时间】:2018-12-08 18:34:03
【问题描述】:

Listbox2 由表中的项目填充,而该表本身由 listbox1 填充。如果尝试添加到表中包含重复的键,则会引发错误。我希望我的代码通过跳过有问题的问题迭代来处理错误,而不是在循环中途停止。

我的代码如下所示:

Public Sub CopySelected(ByRef frm As Form)

    Dim ctlSource As Control
    Dim intCurrentRow As Integer

    Set ctlSource = Me!listbox1
On Error GoTo nonrelation
    Dim rst As dao.Recordset
    Set rst = CurrentDb.OpenRecordset("Select * from [tempTable]")

    For intCurrentRow = 0 To ctlSource.ListCount - 1
        If ctlSource.Selected(intCurrentRow) Then
            rst.AddNew
            rst![field1] = Forms![myForm]![listbox1].Column(1, intCurrentRow)
            rst![field2] = Forms![myForm]![listbox1].Column(0, intCurrentRow)
            rst.Update
            Forms![myForm]!listbox2.Requery
        End If
    Next intCurrentRow
    Forms![myForm]!listbox2.Requery
done:
    Exit Sub
nonrelation:
    MsgBox Err.Description
End Sub

我知道我必须以某种方式使用“恢复”命令来代替我的MsgBox Err.Description,但我从未使用过它。我想知道如何在我的代码中正确地实现它。谢谢!

【问题讨论】:

  • 我相信您只需将nonnrelation: 放在Next intCurrentRow 上方即可移至下一项。
  • 为什么不修改查询以不跨越重复?对我来说似乎更合适。应该保留错误处理来处理真正的错误
  • 我的意思是,查询不接受重复。不能在 tempTable 中插入重复项,因此在 listbox2 中也是不可能的。但是,如果尝试,将引发错误。不过,我不知道我是否理解您的评论。
  • Next 之前添加标签,例如skip: - 然后在MsgBox 调用下添加Resume skip。也就是说,@OleEHDufour 有一个非常真实和重要的观点:错误处理不应该用于控制流。有什么错误?可以完全避免吗?
  • 黄金法则#1:用户不会犯错,程序员会犯错! ;-) 看起来您需要额外的逻辑来验证您是否要插入重复键。祝你好运!

标签: vba ms-access for-loop error-handling resume


【解决方案1】:

您可以使用辅助函数检查记录是否存在,如果不存在则仅添加。

Public Function Exists(ByVal Value As String) As Boolean
    Exists = DCount("*","tempTable","[field1]='" & Value & "'") > 0
End Function

然后在您的循环中检查每条记录,然后再尝试插入。

For intCurrentRow = 0 To ctlSource.ListCount - 1
    If ctlSource.Selected(intCurrentRow) Then
        If Not Exists(Forms![myForm]![listbox1].Column(1, intCurrentRow)) Then
            With rst
                .AddNew
                ![field1] = Forms![myForm]![listbox1].Column(1, intCurrentRow)
                ![field2] = Forms![myForm]![listbox1].Column(0, intCurrentRow)
                .Update
            End With
            Forms![myForm]!listbox2.Requery
        End If
    End If
Next intCurrentRow

请注意,上面的示例需要 String。如果是数字,则需要删除 ' ' 引号。

【讨论】:

    猜你喜欢
    • 2015-05-03
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    • 2021-07-11
    相关资源
    最近更新 更多