2

Just started with Access VBA today and imagine this is a simple fix. The program calculates total guests in each service category. I must be missing something simple.

Public Sub CalculateTotalGuestsForEachService()

'Declare variables
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim intTotalParty As Integer

'Set the current database
Set db = CurrentDb

'Set the recordset
Set rst = db.OpenRecordset("Select Orders.* From Orders Where ServiceID = 1")

'Cycle through the records
Do While Not rst.EOF
    intTotalParty = intTotalParty + rst!NoInParty
rst.MoveNext
Loop

'Display total amount
MsgBox "The total is " & intTotalParty

'Close the recordset
rst.Close
Set rst = Nothing
Set db = Nothing   

End Sub
3
  • Is the field NoInParty NULL in any of the records? Commented Nov 17, 2020 at 7:52
  • "the record is a zero"? VBA does not treat NULL values as zero, and you cannot add a NULL value to a number, it has to be a number. Check to see if it's NULL before trying to add it. Commented Nov 17, 2020 at 7:56
  • 1
    Nulls are not considered, they either are nulls or they aren't. If there is a null, you cannot add that to a number. If you want to treat your nulls as zeroes, use the NZ function. But what you should really do is db.OpenRecordset("Select sum(NoInParty) From Orders Where ServiceID = 1") instead of fetching all those irrelevant columns and rows and slowly adding them one by one on the client. Commented Nov 17, 2020 at 7:58

1 Answer 1

1

If any record has a Null value, apply Nz:

intTotalParty = intTotalParty + Nz(rst!NoInParty.Value, 0)

or, you could let the query sum the values:

'Set the recordset
Set rst = db.OpenRecordset("Select Sum(NoInParty) As TotalParty From Orders Where ServiceID = 1")
If rst.RecordCount = 1 Then
    intTotalParty = Nz(rst!TotalParty.Value)
End If
Sign up to request clarification or add additional context in comments.

1 Comment

or use DSum - no need to deal with a recordset

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.