I know you can number the results of a query (1,2,3,4…..), but is it possible to begin the count again within the query, based on a value change? Example: Pet_Names_Qry: Dogs: 1. Rex, 2. Rover, 3. Ruff. Cats: 1. Tabby, 2. Snow Bell, etc…???
![]() |
Patch reliability is unclear. Unless you have an immediate, pressing need to install a specific patch, don't do it. |
SIGN IN | Not a member? | REGISTER | PLUS MEMBERSHIP |
-
Number query results by group (2000)
Home » Forums » AskWoody support » Productivity software by function » MS Access and database help » Number query results by group (2000)
- This topic has 15 replies, 4 voices, and was last updated 21 years, 1 month ago.
AuthorTopicWSwillyboy
AskWoody LoungerMay 6, 2003 at 3:47 pm #387072Viewing 0 reply threadsAuthorReplies-
WSHansV
AskWoody LoungerMay 6, 2003 at 6:28 pm #674245It can probably be done in a query, but it’s rather artificial. It is very easy in a report: add a grouping level for species (or whatever the field you want to group on is named). Put a text box in the detail section with Control Source =1, and set its Running Sum property (in the Data tab) to Over Groups. Can you live with that?
-
WSwillyboy
AskWoody LoungerMay 7, 2003 at 12:27 pm #674469 -
WSHansV
AskWoody LoungerMay 7, 2003 at 1:29 pm #674485OK, here you go, but what I have come up with is s l o o o w w w.
You will need a unique identifier for the groups and a unique identifier for the records. These are used in the function below; it is an extended version of an example from Microsoft.
Function GetLineNumber(SourceName As String, KeyName As String, _
KeyValue, GroupName As String, GroupValue) As LongDim rst As DAO.Recordset
Dim lngCount As Long
Dim strWhere As StringOn Error GoTo Err_GetLineNumber
Set rst = CurrentDb.OpenRecordset(SourceName)
strWhere = BuildCriteria(GroupName, rst.Fields(GroupName).Type, GroupValue)
rst.CloseSet rst = CurrentDb.OpenRecordset(“SELECT * FROM ” & SourceName & ” WHERE ” & strWhere)
‘ Find the current record.
rst.FindFirst BuildCriteria(KeyName, rst.Fields(KeyName).Type, KeyValue)‘ Loop backward, counting the lines.
Do Until rst.BOF
lngCount = lngCount + 1
rst.MovePrevious
LoopBye_GetLineNumber:
‘ Return the result.
GetLineNumber = lngCount
rst.Close
Set rst = Nothing
Exit FunctionErr_GetLineNumber:
lngCount = 0
Resume Bye_GetLineNumber
End FunctionThis function takes 5 arguments:
- SourceName is the name of a query. It must be sorted by the group field you want to use for counting.
- KeyName is the name of a field that uniquely identifies records (an AutoNumber field for instance).
- KeyValue is the value of this field in the record whose number you want to determine.
- GroupValue is the name of a field that uniquely identifies the groups.
- GroupValue is the value of this field in the record whose number you want to determine.
[/list]The function uses DAO, so you must set a reference to the Microsoft DAO 3.x Object Library in the Visual Basic Editor (Tools | References…)You must first create a query that sort the records by group. Then create a new query based on the first one; add a calculated field with the above function. For example:
N:GetLineNumber(“qryProducts”,”ProductID”,[ProductID],”CategoryID”,[CategoryID])
to calculate a line number in a query based on qryProducts; ProductID is the record identifier and CategoryID is the group identifier.
I have attached a zipped Access 97 database that demonstrates this using the Categories and Products tables from the Northwind sample database.
-
WSwillyboy
AskWoody Lounger
-
-
-
WSpatt
AskWoody Lounger -
WShasse
AskWoody Lounger -
WShasse
AskWoody LoungerApril 9, 2004 at 7:36 am #812475Would you mind to have a look at the attachment? I might have found a faster solution .
However, testing the function in Hans’ previous solution generates an error!
Abbreviation used: P(seudo)A(uto)N(umber)There are two functions: one which ‘autonumbers’ all through the recordset and one that restarts when a new group begins (listed below).
Further limitations:
– use only in calculated fields in queries with a unique key (ID)
– no renumbering when user adds custom sort order using the ‘A-Z’ & ‘Z-A’-buttons in datasheet view! Function uses actual SQLFurther to do:
– error handling
– use one PAN(…) function with optional ‘grouping’ argument (requires some rewriting I guess)
– check out: behaviour when user enters new records in query & application in forms,…
– large recordsets: use ‘findfirst’ to go to first record of group X (faster then looping all through)Public Function PAN_Group(QueryName As String, KeyName As String, KeyValue As Variant, GroupField As String) As Long
Dim rst As Recordset ‘DAO.Recordset
Dim lngI As Long
Dim varCurGroup‘Exit Function ‘Programming help: when error occurs, it repeats itself for each record. So: with first occurence choose ‘debug’, remove the “‘” at the beginning of this line and save before stopping execution (otherwise, an error will pop up for each record!)
‘Initialize
Set rst = CurrentDb.OpenRecordset(QueryName, dbOpenDynaset)
rst.MoveLast
rst.MoveFirst
lngI = 1
PAN_Group = 0
varCurGroup = rst(GroupField)‘Loop through query
Do While Not rst.EOF
‘Start renumbering when new group starts (i.e. when the ‘group’ field changes to a new value)
If Not rst(GroupField) = varCurGroup Then
lngI = 1
varCurGroup = rst(GroupField)
End If
‘If current record is the one with the required ID value, then pseudo-autonumber (& exit)
If rst(KeyName) = KeyValue Then
PAN_Group = lngI
Exit Function
End If
rst.MoveNext
lngI = lngI + 1
LoopEnd Function
-
WSHansV
AskWoody LoungerApril 9, 2004 at 11:12 am #812519I had no problem appying your functions in my example. On large recordsets, your method is slightly faster, but both are excruciatingly slow. On a test with a table with a million records, it took 2 minutes and 13 seconds before I regained control with my method, and 2 minutes and 8 seconds with your method.
-
WShasse
AskWoody LoungerApril 9, 2004 at 2:30 pm #812586Argl… are you serious, a million records? I thought Access was just a horse to pull max. some tens of thousands!
Still you’re absolutely right: two minutes is no fun. Have you already tried to use ‘findfirst’ to jump to the first appearance of the group value in the recordset (and start counting there) instead of looping the whole set through one by one before you get there? (Just if you are interested… otherwise I’ll try it out myself – I’ll just have to be creative in order to arrange a million records :-).) -
WShasse
AskWoody LoungerApril 9, 2004 at 2:30 pm #812587Argl… are you serious, a million records? I thought Access was just a horse to pull max. some tens of thousands!
Still you’re absolutely right: two minutes is no fun. Have you already tried to use ‘findfirst’ to jump to the first appearance of the group value in the recordset (and start counting there) instead of looping the whole set through one by one before you get there? (Just if you are interested… otherwise I’ll try it out myself – I’ll just have to be creative in order to arrange a million records :-).) -
WShasse
AskWoody LoungerApril 13, 2004 at 6:39 pm #814176Hans, (and all those others which might be interested)
FYI: apparently (but reasonably too, probably) most time is just spent by loading the recordset. When I ran a 350.000 records query (1) using the function truncated after the ‘set rst = …’ line (so: doing no more than assigning the recordset to a variable), it still needed more than 10″ per individual function call (coming close to your previous measurement).
With a dbOpenForwardOnly recordset typeyou might tweak another second or two from this result, but that’s it, I guess
.
My conclusion: the function’s time loss seems inevitable when so many records are involved, unless a bright mind
could avoid loading the entire recordset or provide an entirely different approach
.
Greetings,
Hasse(1) provided by Excel’s helpful CTRL+D
let-me-fill-down-zillions-of-lines-with-nonsense-feature
-
WShasse
AskWoody LoungerApril 13, 2004 at 6:39 pm #814177Hans, (and all those others which might be interested)
FYI: apparently (but reasonably too, probably) most time is just spent by loading the recordset. When I ran a 350.000 records query (1) using the function truncated after the ‘set rst = …’ line (so: doing no more than assigning the recordset to a variable), it still needed more than 10″ per individual function call (coming close to your previous measurement).
With a dbOpenForwardOnly recordset typeyou might tweak another second or two from this result, but that’s it, I guess
.
My conclusion: the function’s time loss seems inevitable when so many records are involved, unless a bright mind
could avoid loading the entire recordset or provide an entirely different approach
.
Greetings,
Hasse(1) provided by Excel’s helpful CTRL+D
let-me-fill-down-zillions-of-lines-with-nonsense-feature
-
WSHansV
AskWoody LoungerApril 9, 2004 at 11:12 am #812520I had no problem appying your functions in my example. On large recordsets, your method is slightly faster, but both are excruciatingly slow. On a test with a table with a million records, it took 2 minutes and 13 seconds before I regained control with my method, and 2 minutes and 8 seconds with your method.
-
WShasse
AskWoody LoungerApril 9, 2004 at 7:36 am #812476Would you mind to have a look at the attachment? I might have found a faster solution .
However, testing the function in Hans’ previous solution generates an error!
Abbreviation used: P(seudo)A(uto)N(umber)There are two functions: one which ‘autonumbers’ all through the recordset and one that restarts when a new group begins (listed below).
Further limitations:
– use only in calculated fields in queries with a unique key (ID)
– no renumbering when user adds custom sort order using the ‘A-Z’ & ‘Z-A’-buttons in datasheet view! Function uses actual SQLFurther to do:
– error handling
– use one PAN(…) function with optional ‘grouping’ argument (requires some rewriting I guess)
– check out: behaviour when user enters new records in query & application in forms,…
– large recordsets: use ‘findfirst’ to go to first record of group X (faster then looping all through)Public Function PAN_Group(QueryName As String, KeyName As String, KeyValue As Variant, GroupField As String) As Long
Dim rst As Recordset ‘DAO.Recordset
Dim lngI As Long
Dim varCurGroup‘Exit Function ‘Programming help: when error occurs, it repeats itself for each record. So: with first occurence choose ‘debug’, remove the “‘” at the beginning of this line and save before stopping execution (otherwise, an error will pop up for each record!)
‘Initialize
Set rst = CurrentDb.OpenRecordset(QueryName, dbOpenDynaset)
rst.MoveLast
rst.MoveFirst
lngI = 1
PAN_Group = 0
varCurGroup = rst(GroupField)‘Loop through query
Do While Not rst.EOF
‘Start renumbering when new group starts (i.e. when the ‘group’ field changes to a new value)
If Not rst(GroupField) = varCurGroup Then
lngI = 1
varCurGroup = rst(GroupField)
End If
‘If current record is the one with the required ID value, then pseudo-autonumber (& exit)
If rst(KeyName) = KeyValue Then
PAN_Group = lngI
Exit Function
End If
rst.MoveNext
lngI = lngI + 1
LoopEnd Function
-
-
-
WShasse
AskWoody Lounger
-
Viewing 0 reply threads -

Plus Membership
Donations from Plus members keep this site going. You can identify the people who support AskWoody by the Plus badge on their avatars.
AskWoody Plus members not only get access to all of the contents of this site -- including Susan Bradley's frequently updated Patch Watch listing -- they also receive weekly AskWoody Plus Newsletters (formerly Windows Secrets Newsletter) and AskWoody Plus Alerts, emails when there are important breaking developments.
Get Plus!
Welcome to our unique respite from the madness.
It's easy to post questions about Windows 11, Windows 10, Win8.1, Win7, Surface, Office, or browse through our Forums. Post anonymously or register for greater privileges. Keep it civil, please: Decorous Lounge rules strictly enforced. Questions? Contact Customer Support.
Search Newsletters
Search Forums
View the Forum
Search for Topics
Recent Topics
-
Windows 11 ad from Campaign Manager in Windows 10 (Awaiting moderation)
by
Jim McKenna
1 hour, 54 minutes ago -
Phishers extract Millions from HMRC accounts..
by
Microfix
10 hours, 33 minutes ago -
Windows 10 22H2 Update today (5 June) says up-to-date but last was 2025-04
by
Alan_uk
12 hours, 25 minutes ago -
Thoughts on Malwarebytes Scam Guard for Mobile?
by
opti1
15 hours, 33 minutes ago -
Mystical Desktop
by
CWBillow
15 hours, 47 minutes ago -
Meta and Yandex secretly tracked billions of Android users
by
Alex5723
10 hours, 33 minutes ago -
MS-DEFCON 2: Do you need that update?
by
Susan Bradley
5 hours, 58 minutes ago -
CD/DVD drive is no longer recognized
by
WSCape Sand
1 day, 7 hours ago -
Windows 11 24H2 Default Apps stuck on Edge and Adobe Photoshop
by
MikeBravo
1 day, 9 hours ago -
North Face and Cartier customer data stolen in cyber attacks
by
Alex5723
1 day, 7 hours ago -
What is wrong with simple approach?
by
WSSpoke36
1 day ago -
Microsoft-Backed Builder.ai Set for Bankruptcy After Cash Seized
by
Alex5723
1 day, 19 hours ago -
Location, location, location
by
Susan Bradley
9 hours, 46 minutes ago -
Cannot get a task to run a restore point
by
CWBillow
1 day, 20 hours ago -
Frustrating search behavior with Outlook
by
MrJimPhelps
1 day, 11 hours ago -
June 2025 Office non-Security Updates
by
PKCano
2 days, 7 hours ago -
Secure Boot Update Fails after KB5058405 Installed
by
SteveIT
10 hours, 6 minutes ago -
Firefox Red Panda Fun Stuff
by
Lars220
2 days, 7 hours ago -
How start headers and page numbers on page 3?
by
Davidhs
2 days, 17 hours ago -
Attack on LexisNexis Risk Solutions exposes data on 300k +
by
Nibbled To Death By Ducks
1 day, 20 hours ago -
Windows 11 Insider Preview build 26200.5622 released to DEV
by
joep517
3 days, 2 hours ago -
Windows 11 Insider Preview build 26120.4230 (24H2) released to BETA
by
joep517
3 days, 2 hours ago -
MS Excel 2019 Now Prompts to Back Up With OneDrive
by
lmacri
2 days, 16 hours ago -
Firefox 139
by
Charlie
2 days, 8 hours ago -
Who knows what?
by
Will Fastie
1 day, 11 hours ago -
My top ten underappreciated features in Office
by
Peter Deegan
3 days, 3 hours ago -
WAU Manager — It’s your computer, you are in charge!
by
Deanna McElveen
20 hours, 52 minutes ago -
Misbehaving devices
by
Susan Bradley
1 day, 23 hours ago -
.NET 8.0 Desktop Runtime (v8.0.16) – Windows x86 Installer
by
WSmeyerbos
4 days, 9 hours ago -
Neowin poll : What do you plan to do on Windows 10 EOS
by
Alex5723
1 day, 8 hours ago
Recent blog posts
Key Links
Want to Advertise in the free newsletter? How about a gift subscription in honor of a birthday? Send an email to sb@askwoody.com to ask how.
Mastodon profile for DefConPatch
Mastodon profile for AskWoody
Home • About • FAQ • Posts & Privacy • Forums • My Account
Register • Free Newsletter • Plus Membership • Gift Certificates • MS-DEFCON Alerts
Copyright ©2004-2025 by AskWoody Tech LLC. All Rights Reserved.