我正尝试以下列方式以循环方式将销售人员(rsSalespeople)分配给客户(rsCustomers):
自从我处理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
有十个客户和五个销售人员,我想要的结果是:
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吗?有什么想法让这段代码有效吗?
答案 0 :(得分:5)
rsSalespeople.EOF并不表示您何时在最后一行,它表示您在最后一行过去的时间。
因此,当你的条件命中最后一个销售员EOF是假的,所以它做一个movenext(使EOF成为真)然后下一个循环操作在rsSalespeople的“EOF行”上操作,你不能从中提取值,因此错误。
请改为尝试:
rsSalespeople.MoveNext
If (rsSalespeople.EOF) Then
rsSalespeople.MoveFirst
End If