目标:我正在编写一个循环以浏览表格,行逐行,评估字段是否互相匹配,然后移动到下一个记录(行(并重新评估。我最终想从中构建一个不断增长的字符串,但是现在我无法将代码转到下一个循环。该值表明代码仅评估第一个记录并重复自身。
我尝试将行'exdif.movenext'移至循环中,如果没有更改。
Option Compare Database
Option Explicit
Sub Export_Library_Compare_Process()
'Identify the variables
Dim Tang As DAO.Database
Dim ExDif As DAO.Recordset
Dim Field01a As DAO.Field
Dim Field01b As DAO.Field
Dim ID As DAO.Field
'Set the database and recordsets to database and tables
Set Tang = CurrentDb
Set ExDif = Tang.OpenRecordset("Staging_LOG_ExportDifferences")
Set Field01a = ExDif.Fields("a_Client Name")
Set Field01b = ExDif.Fields("b_Client Name")
Set ID = ExDif.Fields("ID")
'Start a series to look to see what matches
Do While Not ExDif.EOF
'Move to first row in table
ExDif.MoveFirst
'Field 01 - Client Name
If Field01a.Value <> Field01a.Value Then
MsgBox "Client Name does not match"
Else: MsgBox "Client Name matches"
'Move to next record (row) in table
ExDif.MoveNext
'End the Else - If
End If
'End Loop
Loop
几个问题。
Set ExDif = Tang.OpenRecordset("Staging_LOG_ExportDifferences") Set Field01a = ExDif.Fields("a_Client Name") Set Field01b = ExDif.Fields("b_Client Name") Set ID = ExDif.Fields("ID")
此代码在知道有记录之前就开始阅读记录集。如果记录集是空的(即记录集既是BOF
和EOF
(,则这些后续分配将失败,而错误。这些作业应在录音循环中。
ExDif.MoveFirst
您在第一个记录上已经;在每次迭代中,将光标无条件地移回第一个记录,这就是为什么您的循环卡在第一个记录上的原因。删除这条线。
If Field01a.Value <> Field01a.Value Then
此表达式将始终对False
进行评估,这是一种启发式恒定表达式,可能是错字。它是要将Field01a
与Field01b
进行比较?
Else: MsgBox "Client Name matches" 'Move to next record (row) in table ExDif.MoveNext 'End the Else - If End If
这种凹痕非常误导,并且非常非常容易出错。考虑:
Else
MsgBox "Client Name matches"
ExDif.MoveNext
End If
现在, .MoveNext
是有条件的(有点 - 请参阅上一个关于条件表达式的观点(,是一个问题:无论循环主体中发生了什么,您都希望在下一个记录上'重做。因此.MoveNext
永远不应该是有条件的。
这应该解决:
Set exportDiffs = Tang.OpenRecordset("Staging_LOG_ExportDifferences")
Do Until exportDiffs.EOF
Dim clientNameA As String
clientNameA = exportDiffs.Fields("a_Client Name").Value
Dim clientNameB As String
clientNameB = exportDiffs.Fields("b_Client Name").Value
If clientNameA <> clientNameB Then
'client name mismatch
GoTo Skip
End If
Dim id As Long
id = exportDiffs.Fields("ID").Value
' do stuff...
Skip:
exportDiffs.MoveNext
Loop
我的工作中有一些异常的安全限制,我对此不起作用。但是我查看了一些访问编程委员会,并找到了这篇文章[https://access-programmers.co.uk/forums/showthread.php?t=171138]"或"做直到"。当我尝试将循环样式切换为"做"时,它效果很好。
做直到exdif.eof