我正在尝试按以下方式以循环方式将销售人员 (rsSalespeople) 分配给客户 (rsCustomers):
- 导航到第一个客户,将第一个销售人员分配给该客户。
- 移至下一个客户。如果 rsSalesPersons 不在 EOF,则移至下一个 SalesPerson;如果 rsSalesPersons 位于 EOF,则 MoveFirst 循环回第一个 SalesPerson。将此(当前)销售人员分配给(当前)客户。
- 重复步骤 2,直到 rsCustomers 位于 EOF(EOF = True,即 End-Of-Recordset)。
自从我处理 VBA 以来已经有一段时间了,所以我有点生疏了,但到目前为止,这是我想到的:
Private Sub Command31_Click()
'On Error GoTo ErrHandler
Dim intCustomer As Integer
Dim intSalesperson As Integer
Dim rsCustomers As DAO.Recordset
Dim rsSalespeople As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT CustomerID, SalespersonID FROM Customers WHERE SalespersonID Is Null"
Set rsCustomers = CurrentDb.OpenRecordset(strSQL)
strSQL = "SELECT SalespersonID FROM Salespeople"
Set rsSalespeople = CurrentDb.OpenRecordset(strSQL)
rsCustomers.MoveFirst
rsSalespeople.MoveFirst
Do While Not rsCustomers.EOF
intCustomer = rsCustomers!CustomerID
intSalesperson = rsSalespeople!SalespersonID
strSQL = "UPDATE Customers SET SalespersonID = " & intSalesperson & " WHERE CustomerID = " & intCustomer
DoCmd.RunSQL (strSQL)
rsCustomers.MoveNext
If Not rsSalespeople.EOF Then
rsSalespeople.MoveNext
Else
rsSalespeople.MoveFirst
End If
Loop
ExitHandler:
Set rsCustomers = Nothing
Set rsSalespeople = Nothing
Exit Sub
ErrHandler:
MsgBox (Err.Description)
Resume ExitHandler
End Sub
我的表定义如下:
Customers
--CustomerID
--Name
--SalespersonID
Salespeople
--SalespersonID
--Name
有 10 名客户和 5 名销售人员,我的预期结果是:
CustomerID--Name--SalespersonID
1---A---1
2---B---2
3---C---3
4---D---4
5---E---5
6---F---1
7---G---2
8---H---3
9---I---4
10---J---5
上面的代码适用于 Salespeople 记录集的初始循环,但在找到记录集末尾时会出错。无论 EOF 如何,它似乎仍然尝试执行 rsSalespeople.MoveFirst 命令。
我没有正确检查 rsSalespeople.EOF 吗?有什么想法可以让这段代码正常工作吗?
rsSalespeople.EOF 并不指示您何时位于最后一行,而是指示您何时超过最后一行。
因此,当您的条件命中最后一个销售人员 EOF 为 false 时,它会执行 movenext (使 EOF 为 true),然后循环的下一次遍历将在 rsSalespeople 的“EOF 行”上进行操作,您无法从中提取值,因此会出现错误。
试试这个:
rsSalespeople.MoveNext
If (rsSalespeople.EOF) Then
rsSalespeople.MoveFirst
End If
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)