You are welcome!
Just for fun, I wanted to see if I could do it like I said in Access. It worked. Here is how I did it.
- Add the Grouping fields to the base table, if one is not already there.
- Create a query based on the table that returns the Line Number and Grouping fields, and have the query sorted by the Line Number field.
(I named my query "MySortQuery" and assumed the field names are "LineNum" and "Grouping")
- Place the following VBA code in a module:
Code:
Public Sub AddGrouping()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim prevLineNum As Integer
Dim lineNum As Integer
Dim groupNum As Integer
' Open up query in recordset
Set db = CurrentDb
Set rst = db.OpenRecordset("MySortQuery", dbOpenDynaset) 'enter your query name
' Initialize variables
prevLineNum = -999
groupNum = 0
' Loop through recordset
rst.MoveFirst
Do While Not rst.EOF
' Capture line number of current record
lineNum = rst!lineNum 'the text after rst! should match the field name in the query
' Compare line number to previous line number and adjust grouping accordingly
'MsgBox "lineNum: " & lineNum & vbCrLf & "prevLineNum: " & prevLineNum
If lineNum - prevLineNum > 1 Then groupNum = groupNum + 1
' Assign grouping number to current record
With rst
.Edit
.Fields("Grouping") = groupNum 'field name needs to match query
.Update
.MoveNext
End With
' Set previous line number
prevLineNum = lineNum
Loop
' Close recordset
rst.Close
MsgBox "Grouping numbers assignement complete!"
End Sub
- Create a form and place a command button on the form. Then have the command button's On Click event call the procedure, i.e.
Code:
Private Sub Command1_Click()
Call AddGrouping
End Sub
- Click on the button to run the code and update the Groupings.
Note: If you are using a version of Office older than 2007, you may need to go to the VB Editor, select Tools -> References and find and select a Microsoft DAO Object Library (pick the highest numbered one listed). Otherwise, you may get errors when it tries to compile the code.