Sorry I think you have misinterpretted. I want to allocate a salesperson to all records which dont have a salesperson allocated. The status shouldnt matter. The status matters in the second third of the code where we are counting the number of leads. This is where I want to count only the 'active' (or number 2 as you say) leads. If I count all the leads allocated to a salesperson then I will be counting dead leads and therefore if a salesperson has only a bunch of dead leads they will still never come to the top of the pile to be allocated the next lead. Does this make sense? I am so close thanks to your help. I am getting the error '3122 - you are trying to execute a query thatdosnt include the aggregate function status as part of the expression'. I know its to do with my syntax again and have highlighted where I think the issue is. I am sure this is where my issue is as this code works perfectly until I try to add in the status thing. An I thought it would be so easy to add later
Private Sub AllocateLeads_Click()
Dim db As DAO.Database
Dim LD As DAO.Recordset
Dim SP As DAO.Recordset
On Error GoTo BadNews
Set db = CurrentDb
' Get the Leads that do not have a Sales Person assigned.
Set LD = db.OpenRecordset( _
"Select ClientID " & _
"From Tbl_Client " & _
"Where Trim$(StaffAllocated & '') = ''", dbOpenSnapshot)
Do Until LD.EOF
' Find the Sales Person with the fewest leads. If there's a tie then
' just arbitrarily pick one.
Set SP = db.OpenRecordset( _
"SELECT S.ID[highlight #EDD400], c.status " & _[/highlight]" FROM Tbl_Staff As S LEFT JOIN Tbl_Client As C" & _
" ON S.ID=C.StaffAllocated" & _
" WHERE S.Available=yes [highlight #FCE94F]AND c.status = 2" & _[/highlight]" GROUP BY S.ID" & _
" ORDER BY Count(C.StaffAllocated)")
' Assign this lead to the salesperson. The field StaffAllocated is
' updated to the sales person found in recordset SP. AND we are
' doing that to the Tbl_Client record for the client LD![ClientID]
Dim strID As String
strID = Replace(SP![ID], "'", "''")
db.Execute "UPDATE Tbl_Client" & _
" SET StaffAllocated='" & strID & "'" & _
",FirstContact='" & strID & "'" & _
"WHERE ClientID = " & LD![ClientID] & ";", dbFailOnError
LD.MoveNext
Loop
Exit_Sub:
MsgBox "All new leads have been allocated"
Set LD = Nothing
Set SP = Nothing
Set db = Nothing
Exit Sub
BadNews:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_Sub:
End Sub