I needed to generate an output from my Access database that was unavailable using standard functions. I did extensive searching, but when I found example code - it ultimately f
You can do this with an SQL query and a dash of VBA.
Insert a VBA module into Access, with the following code:
'Module level variables; values will persist between function calls
Dim lastValue As String
Dim currentIndex As Integer
Public Function GetIndex(Value) As Integer
If Value <> lastValue Then currentIndex = currentIndex + 1
GetIndex = currentIndex
End Function
Public Sub Reset()
lastValue = ""
currentIndex = 0
End Sub
Then you can use the function as in the following query:
SELECT Table1.Field1, GetIndex([Field1]) AS Expr1
FROM Table1;
Just make sure to call Reset each time before you want to run the query; otherwise the last value will still be preserved from the previous query run.
When values later repeat themselves (e.g. a,b,a), the previous code will treat them as a new value. If you want the same value to return the same index for the entire length of a query, you can use a Dictionary:
Dim dict As New Scripting.Dictionary
Public Function GetIndex(Value As String) As Integer
If Not dict.Exists(Value) Then dict(Value) = UBound(dict.Keys) + 1 'starting from 1
GetIndex = dict(Value)
End Function
Public Sub Reset()
Set dict = New Scripting.Dictionary
End Sub