首页 > 解决方案 > 访问vba:出错时进入下一次迭代

问题描述

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

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

标签: vbams-accessfor-looperror-handlingresume

解决方案


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

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. 如果是数字,您将需要删除' '引号。


推荐阅读