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

前端 未结 3 1566
渐次进展
渐次进展 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
    
    0 讨论(0)
  • 2021-01-26 18:25

    I'm not quite sure what you're trying to achieve with that convoluted function of yours. Do you want to print the position in the alphabet for each letter you read from your database? That could be easily achieved with something like this:

    filename = "D:\Temp\_test.txt"
    
    Set rst = CurrentDb.OpenRecordset(QryName, dbOpenDynaset)
    
    Set f= CreateObject("Scripting.FileSystemObject").OpenTextFile(filename, 8, True)
    Do Until rst.EOF
      v = rst.Fields(fldName).Value
      f.WriteLine v & ", " & (Asc(v) - 96)
      rst.MoveNext
    Loop
    f.Close
    
    0 讨论(0)
  • 2021-01-26 18:37

    "Unique" means "Dictionary" in VBScript. So use one as in:

    >> Set d = CreateObject("Scripting.Dictionary")
    >> For Each c In Split("a b b b c c d")
    >>     If Not d.Exists(c) Then
    >>        d(c) = 1 + d.Count
    >>     End If
    >> Next
    >> For Each c In Split("a b b b c c d")
    >>     WScript.Echo c, d(c)
    >> Next
    >>
    a 1
    b 2
    b 2
    b 2
    c 3
    c 3
    d 4
    

    where "c 3" means: "c is the 3rd unique item found in the source collection".

    0 讨论(0)
提交回复
热议问题