下午好,我需要一些帮助。有十几种方法可以解决我即将要求的但最快的方法(我希望能够忽略一些)
我现在有两种方法,慢速和超低速(2更快)
如果生成的随机数在链表中不存在,那么它所做的就是创建新记录。表变得越大,代码运行得越慢。在不久的将来,添加几个代码可能需要几天时间。
添加记录的代码:
Sub MakenNieuweNummers(AantalNieuweNummers As Long, strProduct As String, strBatch As String)
Dim strCode As String
Dim AantalNummersGemaakt As Long
Dim strSQL As String
'Vul hier het aantal nieuwe gewenste nummers in om de database mee uit te breiden
Do While AantalNummersGemaakt < AantalNieuweNummers
DoEvents
strCode = randomstring(6)
If DCount("code", "tblNummers", "code = '" & strCode & "'") = 0 Then
strSQL = "insert into tblNummers " & _
"(code,actief,printdatum,product,batchnummer) " & _
"VALUES ('" & strCode & "',TRUE,#" & Format(Date, "MM-DD-YYYY") & "#,'" & strProduct & "','" & strBatch & "')"
dbLocal().Execute strSQL
AantalNummersGemaakt = AantalNummersGemaakt + 1
End If
Loop
End Sub
Sub MakenNieuweNummers2(AantalNieuweNummers As Long, strProduct As String, strBatch As String)
Dim strCode As String
Dim AantalNummersGemaakt As Long
Dim strSQL As String
'Vul hier het aantal nieuwe gewenste nummers in om de database mee uit te breiden
Do While AantalNummersGemaakt < AantalNieuweNummers
DoEvents
strCode = randomstring(6)
If dbLocal().OpenRecordset("SELECT Count([ID]) AS [CountALL] FROM tblNummers WHERE code='" & strCode & "';")![CountALL] = 0 Then
strSQL = "insert into tblNummers " & _
"(code,actief,printdatum,product,batchnummer) " & _
"VALUES ('" & strCode & "',TRUE,#" & Format(Date, "MM-DD-YYYY") & "#,'" & strProduct & "','" & strBatch & "')"
dbLocal().Execute strSQL
AantalNummersGemaakt = AantalNummersGemaakt + 1
End If
Loop
End Sub
也是从函数
返回的随机字符串的代码Function randomstring(Optional iLengte As Integer) As String
If IsMissing(iLengte) Then
iLengte = 6
End If
Randomize
Do While Len(randomstring) < iLengte
randomstring = randomstring & Mid(sReeks, Int((Len(sReeks)) * Rnd) + 1, 1)
Loop
End Function
非常感谢任何帮助。
提前感谢。
答案 0 :(得分:0)
回答我自己的问题......
我通过保持记录集处于打开状态并使用&#39; .addNew&#39;添加新条目来提高性能。
在每个周期之后,我将'更新'#39;保存更改的记录集。
因为每个新条目都将填充一个唯一的索引字段。
当双重发生时,这可能最终引发错误3022
我将使用错误处理程序捕获此错误并在更新之前恢复到标记,并在'.Update'之前尝试该字段的另一个值
这就是它的样子:
Sub MakenNieuweNummers(AantalNieuweNummers As Long, strProduct As String, strBatch As String)
On Error GoTo MakenNieuweNummers_err
Dim AantalNummersGemaakt As Long
Dim rst As DAO.Recordset
Set rst = dbLocal().OpenRecordset("tblNummers", , dbFailOnError)
With rst
Do While AantalNummersGemaakt < AantalNieuweNummers
DoEvents
.AddNew
MakenNieuweNummers_next:
!code = randomstring(6)
.Update 'Error 3022 in case of double, will let errorhandler fix this.
AantalNummersGemaakt = AantalNummersGemaakt + 1
Loop
End With
MakenNieuweNummers_Exit:
rst.Close
Set rst = Nothing
Exit Sub
MakenNieuweNummers_err:
If Err.Number = 3022 Then
Resume MakenNieuweNummers_next
Else
MsgBox Err.Number & vbNewLine & Err.Description, vbCritical
Resume MakenNieuweNummers_Exit
End If
End Sub
如果有更多表现,请回复。总是喜欢学习更多!