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 20 years, 12 months 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
-
WARNING about Nvidia driver version 572.83 and 4000/5000 series cards
by
Bob99
1 hour, 48 minutes ago -
Creating an Index in Word 365
by
CWBillow
10 hours ago -
Coming at Word 365 and Table of Contents
by
CWBillow
10 hours, 5 minutes ago -
Windows 11 Insider Preview Build 22635.5170 (23H2) released to BETA
by
joep517
15 hours, 1 minute ago -
Has the Microsoft Account Sharing Problem Been Fixed?
by
jknauth
18 hours, 26 minutes ago -
W11 24H2 – Susan Bradley
by
G Pickerell
20 hours, 22 minutes ago -
7 tips to get the most out of Windows 11
by
Alex5723
18 hours, 23 minutes ago -
Using Office apps with non-Microsoft cloud services
by
Peter Deegan
11 hours, 45 minutes ago -
I installed Windows 11 24H2
by
Will Fastie
24 minutes ago -
NotifyIcons — Put that System tray to work!
by
Deanna McElveen
23 hours, 49 minutes ago -
Decisions to be made before moving to Windows 11
by
Susan Bradley
19 minutes ago -
Port of Seattle says ransomware breach impacts 90,000 people
by
Nibbled To Death By Ducks
1 day, 8 hours ago -
Looking for personal finance software with budgeting capabilities
by
cellsee6
16 hours, 16 minutes ago -
ATT/Yahoo Secure Mail Key
by
Lil88reb
16 hours, 31 minutes ago -
Devices with apps using sprotect.sys driver might stop responding
by
Alex5723
2 days, 1 hour ago -
Neowin – 20 times computers embarrassed themselves with public BSODs and goofups
by
EP
2 days, 9 hours ago -
Slow Down in Windows 10 performance after March 2025 updates ??
by
arbrich
1 day, 11 hours ago -
Mail from certain domains not delivered to my outlook.com address
by
pumphouse
1 day, 18 hours ago -
Is data that is in OneDrive also taking up space on my computer?
by
WShollis1818
2 days, 4 hours ago -
Nvidia just fixed an AMD Linux bug
by
Alex5723
3 days, 20 hours ago -
50 years and counting
by
Susan Bradley
18 hours, 41 minutes ago -
Fix Bluetooth Device Failed to Delete in Windows Settings
by
Drcard:))
21 hours, 30 minutes ago -
Licensing and pricing updates for on-premises server products coming July 2025
by
Alex5723
4 days, 7 hours ago -
Edge : Deprecating window.external.getHostEnvironmentValue()
by
Alex5723
4 days, 7 hours ago -
Rethinking Extension Data Consent: Clarity, Consistency, and Control
by
Alex5723
4 days, 7 hours ago -
OneNote and MS Word 365
by
CWBillow
4 days, 9 hours ago -
Ultimate Mac Buyers Guide 2025: Which Mac is Right For You?
by
Alex5723
4 days, 9 hours ago -
Intel Unison support ends on Windows 11 in June
by
Alex5723
4 days, 9 hours ago -
April 2025 — still issues with AMD + 24H2
by
Kevin Jones
2 days, 1 hour ago -
Windows 11 Insider Preview build 26200.5518 released to DEV
by
joep517
4 days, 21 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.