我想通过以下方式分配在一个循环的方式销售人员(rsSalespeople)给客户(rsCustomers)循环:通过记录与VBA
- 浏览到第一个客户,将第一个营业员的顾客。
- 转到下一位客户。如果rsSalesPersons不在EOF处,请转到Next SalesPerson;如果rsSalesPersons在EOF处,则MoveFirst将循环回第一个SalesPerson。将此(当前)SalesPerson分配给(当前)客户。
- 重复步骤2直到rsCustomers在EOF处(EOF = True,即结束记录集)。
它已经一段时间,因为我处理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
随着十个客户和销售人员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正常吗?任何想法让这个代码工作?
不回答你的问题,但为什么运行在你的循环中的更新语句,如果你已经有一个开放的DAO记录,而不是只更新当前行与rsCustomers !SalespersonID = rsSalespeople!SalespersonID – JohnFx 2010-04-05 16:00:01
根据您添加新客户多少次并且必须运行此批次,您列表中的前几名销售人员将获得不成比例的分配客户数量。也许你可以按现有客户的数量对销售人员名单进行分类? – JeffO 2010-04-05 17:39:22