Count and insert unique values - Can this code be optimized?

前端 未结 3 1612
渐次进展
渐次进展 2021-01-26 18:09

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

3条回答
  •  清歌不尽
    2021-01-26 18:18

    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
    

提交回复
热议问题