vba - 访问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
,但我从未使用过它。我想知道如何在我的代码中正确地实现它。谢谢!
解决方案
您可以使用辅助函数检查记录是否存在,如果不存在则仅添加。
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
. 如果是数字,您将需要删除'
'
引号。
推荐阅读
- python - docker中的python烧瓶应用程序没有在前端刷新图像
- tensorflow - Android、TensorFlow 和 Pytorch 中的浮点运算结果不同
- c++ - 如何读取函数“min”中的参数?
- python-3.x - 带有“图表”的图像显示不工作 | PySimpleGUI - sg.Graph
- shell - 用另一个变量替换一个变量中的字符串
- oracle - 如何使用 oracle sql 从包含从 944900000 到 944999999 的数字的表中生成 1000 的 start_no 和 end_no 拆分
- python - 为什么在尝试将列表加入字符串时出现类型错误?
- swiftui - SwiftUI DatePicker 不翻译 titleKey
- swift - 无法跨导航视图更改变量
- tfs-2018 - TFS 2018 无法识别 SQL Server 2019