Share via

Using VBA in Access how can I find the number of records in a table that have a unique field value

Anonymous
2024-04-21T21:20:49+00:00

I want to find the number of records in a table with a unique value in a specific field:

I have a table called Encounters and it has a field Patient, which has a long integer in it. I want to count the number of records that have unique Patient fields, i.e. don't count records with the same patient more than once.

Microsoft 365 and Office | Access | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

  1. Anonymous
    2024-04-22T12:05:50+00:00

    You might like to take a look at DatabaseBasics.zip my public databases folder at:

    https://onedrive.live.com/?cid=44CC60D7FEA42912&id=44CC60D7FEA42912!169

    In this little demo file, selecting the following item in the opening form:

        14. Returning a count of distinct values by means of a subquery

    opens a form which illustrates how to do this by using a subquery to return distinct values, then counting these in the outer query:

    SELECT City, Region, COUNT(*) AS EmployerCount

    FROM (SELECT DISTINCT Cities.CityID, City, Region, EmployerID

                 FROM Regions INNER JOIN ((Cities INNER JOIN Contacts

                 ON Cities.CityID = Contacts.CityID) INNER JOIN ContactEmployers

                 ON Contacts.ContactID = ContactEmployers.ContactID)

                 ON Regions.RegionID = Cities.RegionID)

    GROUP BY City, Region, CityID;

    This returns the distinct number of employers of contacts located in each city. In VBA you could call the DLookup function to return an employer count value for any one or more cities.

    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Anonymous
    2024-04-22T14:34:52+00:00

    Perfect! Thanks-

    0 comments No comments
  2. ScottGem 68,810 Reputation points Volunteer Moderator
    2024-04-22T01:56:36+00:00

    If you want to return this number in VBA, create a query:

    SELECT DISTINCT Patient FROM Encounters;

    Then in VBA use

    x=DCOUNT("*","queryname")

    0 comments No comments
  3. Tom van Stiphout 40,201 Reputation points MVP Volunteer Moderator
    2024-04-21T21:23:51+00:00

    select count(*) as theCount from (select distinct PatientID from YourTable);

    The general technique is explained here.

    0 comments No comments