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

你说的曾经没有我的故事 提交于 2019-12-02 08:36:04

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

"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".

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!