【发布时间】:2014-02-20 01:01:20
【问题描述】:
我有一段代码从表中读取信息并将其插入到带有主键的表中。第一个表是由许多不同的人输入的用户,第二个是我要清理的表
为了让您了解会发生什么,下面的伪代码应该会有所帮助
- 记录被读入数组
- 然后将记录插入到表中,其中主键是数组中唯一标识符的主键
- 如果表中已存在唯一标识符,则数据库会抛出错误(不是 Access 数据库)
- 错误消息与试图插入的记录一起被捕获。违规记录现在被放入错误表以供日后查看
- 在抛出错误消息的地方恢复
问题是代码在执行查询的地方恢复,而不是在循环开始时再次在这种情况下在行 Set rs = cmdSQLData.Execute() 实际上,这意味着它永远试图插入相同的记录
在我的错误处理程序中,我将循环增加一条记录,因此它现在尝试插入下一条记录。不幸的是,接下来的简历中没有考虑到这一点
在实践中我想要的是循环在错误处理程序中增加 1,然后循环尝试插入下一条记录
伪代码
intNumberRows = UBound(myArray, 2) + 1 ' number of records/rows in the array
rowcounter = 0
' Append the Rows of local Table to the temp table
For rowcounter = rowcounter To intNumberRows - 1
' Values X Y Z in this case records contained with the array being looped and inserted
AppendQuery = "INSERT INTO TABLE VALUES(X,Z etc....)
cmdSQLData.CommandText = AppendQuery
cmdSQLData.CommandType = adCmdText
cmdSQLData.CommandTimeout = 60
Set rs = cmdSQLData.Execute()
Next
伪错误处理代码
ErrorHandler:
If (Len(Err.Description) > 0) Then
Debug.Print Err.Description
End If
Debug.Print Err.Number
Debug.Print AppendQuery
' Create Error Table For Upload and resume Inserting of records
If (Err.Number = -2147217900) Then
runfunc = CreateErrorTable(variables)
If runfunc = True Then
rowcounter = rowcounter + 1
Else:
GoTo EndFunction
End If
End If
EndFunction:
cn.Close
Set cn = Nothing
Set rs = Nothing
Set cmdSQLData = Nothing
【问题讨论】:
标签: vba ms-access error-handling