我有一个VBA宏,可以将结果连接起来,一天中有多个结果。它从excel电子表格中检索数据作为ADODB.Recordset。宏会找到要处理的行,并在以1开头的新列中填充值,并根据需要递增。
Set preprocessRng = Range(Cells(2, 28), Cells(30093, 28))
For i = 1 To 98
resultConCat = ""
sql = "SELECT [Result] FROM [output$A1:BA30093] WHERE PreProcess = CInt(" & i & ");"
rs.Open sql, dbs, adOpenStatic, adLockOptimistic
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
If resultConCat = "" Then
resultConCat = rs.Fields(0).Value
Else
resultConCat = resultConCat & " / " & rs.Fields(0).Value
End If
.MoveNext
Wend
Set firstCell = preprocessRng.Find(CInt(i))
Set aCell = preprocessRng.Find(CInt(i))
Do While Not aCell Is Nothing
Cells(aCell.Row, 27).Value = CStr(resultConCat)
Set aCell = preprocessRng.FindNext(After:=aCell)
If aCell.Address = firstCell.Address Then Exit Do
Loop
End If
.Close
End With
Next i
问题在于,PreProcess = 1时会有结果,但是此查询返回0行。当sql = PreProcess = 2时,返回的结果集实际上是PreProcess = 1的地方。此模式一直持续到PreProcess = 60,其中返回的记录集实际上是PreProcess = 59和60。然后从61开始,返回正确的记录集。
Actual Results Vs. Desired Results
如果使用相同的数据集重新运行宏,则不会出现问题。 从那以后,我通过从100开始启动PreProcess并从那里递增来解决了这个问题。
Set preprocessRng = Range(Cells(2, 28), Cells(30093, 28))
For i = 1 To 98
resultConCat = ""
sql = "SELECT [Result] FROM [output$A1:BA30093] WHERE PreProcess = CInt(" & i + 100 & ");" 'modified
rs.Open sql, dbs, adOpenStatic, adLockOptimistic
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
If resultConCat = "" Then
resultConCat = rs.Fields(0).Value
Else
resultConCat = resultConCat & " / " & rs.Fields(0).Value
End If
.MoveNext
Wend
Set firstCell = preprocessRng.Find(CInt(i + 100)) 'modified
Set aCell = preprocessRng.Find(CInt(i + 100)) 'modified
Do While Not aCell Is Nothing
Cells(aCell.Row, 27).Value = CStr(resultConCat)
Set aCell = preprocessRng.FindNext(After:=aCell)
If aCell.Address = firstCell.Address Then Exit Do
Loop
End If
.Close
End With
Next i
我有一种解决方法,但是仍然想知道为什么会发生这种情况吗?我已经详尽地搜索了此信息,却没有发现与此问题类似的东西。欢迎发表评论和建议。