access vba: 出错时转到下一次迭代

access vba: go to next iteration on error

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

我的代码看起来像这样:

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

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

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

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