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
-
24H2 has suppressed my favoured spider
by
Davidhs
3 hours, 3 minutes ago -
GeForce RTX 5060 in certain motherboards could experience blank screens
by
Alex5723
7 hours, 11 minutes ago -
MS Office 365 Home on MAC
by
MickIver
1 hour ago -
Google’s Veo3 video generator. Before you ask: yes, everything is AI here
by
Alex5723
21 hours, 14 minutes ago -
Flash Drive Eject Error for Still In Use
by
J9438
22 hours, 47 minutes ago -
Windows 11 Insider Preview build 27863 released to Canary
by
joep517
1 day, 16 hours ago -
Windows 11 Insider Preview build 26120.4161 (24H2) released to BETA
by
joep517
1 day, 16 hours ago -
AI model turns to blackmail when engineers try to take it offline
by
Cybertooth
19 hours, 46 minutes ago -
Migrate off MS365 to Apple Products
by
dmt_3904
20 hours, 35 minutes ago -
Login screen icon
by
CWBillow
10 hours, 57 minutes ago -
AI coming to everything
by
Susan Bradley
6 hours, 56 minutes ago -
Mozilla : Pocket shuts down July 8, 2025, Fakespot shuts down on July 1, 2025
by
Alex5723
2 days, 7 hours ago -
No Screen TurnOff???
by
CWBillow
2 days, 8 hours ago -
Identify a dynamic range to then be used in another formula
by
BigDaddy07
2 days, 8 hours ago -
InfoStealer Malware Data Breach Exposed 184 Million Logins and Passwords
by
Alex5723
2 days, 20 hours ago -
How well does your browser block trackers?
by
n0ads
2 days, 6 hours ago -
You can’t handle me
by
Susan Bradley
5 hours, 22 minutes ago -
Chrome Can Now Change Your Weak Passwords for You
by
Alex5723
1 day, 23 hours ago -
Microsoft: Over 394,000 Windows PCs infected by Lumma malware, affects Chrome..
by
Alex5723
3 days, 7 hours ago -
Signal vs Microsoft’s Recall ; By Default, Signal Doesn’t Recall
by
Alex5723
2 days, 11 hours ago -
Internet Archive : This is where all of The Internet is stored
by
Alex5723
3 days, 8 hours ago -
iPhone 7 Plus and the iPhone 8 on Vantage list
by
Alex5723
3 days, 8 hours ago -
Lumma malware takedown
by
EyesOnWindows
2 days, 20 hours ago -
“kill switches” found in Chinese made power inverters
by
Alex5723
3 days, 16 hours ago -
Windows 11 – InControl vs pausing Windows updates
by
Kathy Stevens
3 days, 16 hours ago -
Meet Gemini in Chrome
by
Alex5723
3 days, 20 hours ago -
DuckDuckGo’s Duck.ai added GPT-4o mini
by
Alex5723
3 days, 21 hours ago -
Trump signs Take It Down Act
by
Alex5723
4 days, 5 hours ago -
Do you have a maintenance window?
by
Susan Bradley
2 days, 9 hours ago -
Freshly discovered bug in OpenPGP.js undermines whole point of encrypted comms
by
Nibbled To Death By Ducks
3 days, 7 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.