a_stead89 a_stead89 - 5 months ago 13
SQL Question

MS ACCESS Counting Records from table based on multiple criteria

I want a text box in Access to update with the number of records found where a manager has an "overdue" record in the table dependent on the manager selected in a combo box, I have the following code but am getting an error:

Private Sub Combo26_AfterUpdate()

Dim rs As DAO.Recordset

Set rs = CurrentDb.OpenRecordset("SELECT Advisor FROM tbltargets WHERE manager = '" & Me.Combo26.Column(0) & "' AND overdue = 'Overdue'")
If rs.EOF Then
Me.Text35 = 0
MsgBox "no overdue records", vbOKOnly
Else
rs.MoveLast
Me.Text35 = rs.RecordCount
rs.Close
End If

End Sub


When I select an option from the combo box it gives me an error "Too few parameters. Expected 1"...

I have similar code which works so am unsure why the above is resulting in an error, could anyone help?

Thank you,

Answer

Check like this

Private Sub Combo26_AfterUpdate()

Dim rs As DAO.Recordset


If IsNull(Combo26.value) Then Exit Sub

Set rs = CurrentDb.OpenRecordset("SELECT COUNT(*) AS CNT FROM tbltargets WHERE manager = '" & Combo26.value & "' AND overdue = 'Overdue'")

If Not rs.BOF Then

    If Nz(rs!CNT, 0) = 0 Then
        Me.Text35 = 0
        MsgBox "no overdue records", vbOKOnly
    Else
        Me.Text35 = rs!CNT
    End If
End If

End Sub
  1. Used combobox.value instead of combobox.column
  2. Changed the SQL to COUNT(*) and adapted the code accordingly to improve perfs.
  3. Added some protection against NULL values (you should really add an Error Handler in this sub)