VBA Word,获取每个不同数组值的不同计数

VBA Word, get distinct count of each distinct array value

在 MS Word 中使用 VBA。我目前在 ArrayList 中有一组数字(请推荐一个更好的选项来存储值列表)我想获得每个值的不同计数(所以 10 = 1 和 10.5 = 4)。我尝试过滤 ArrayList,但我不认为它与 'contains' 的值完全匹配,因此过滤数组和计数对我不起作用(返回所有值)。我尝试了我找到的其他解决方案,但无法正常工作。有人推荐解决方案。

示例数据:10、10.5、10.5、10.5、10.5

arr = myarrayList.toarray
filteredArray = Filter(arr, 10, True, vbTextCompare) // does not filter, since all values 'contain' 10

count10 = Application.Count(Application.Match(arr, Array(10), 0)) //i dont think vba has Match 

occurrences = arr.lastIndexOf(10) - arr.IndexOf(10, 0) + 1  //i dont think vba has lastIndexof

请尝试下一个代码:

Sub filterArray()
   Dim arr, dict As Object, El
   'to exemplify, I build the array as:
   arr = Split("10, 10.5, 10.5, 10.5, 10.5", ", ")
   'you should use the array extracted from your ArrayList...

   Set dict = CreateObject("Scripting.Dictionary")
   For Each El In arr
        If Not dict.Exists(El) Then
            dict.Add El, 1
        Else
            dict(El) = dict(El) + 1
        End If
   Next
   Debug.Print dict(CStr(10))     'the dictionary keys are strings...
   Debug.Print dict(CStr(10.5))
End Sub

已编辑:

请尝试使用整数的下一个版本(在数组中和字典键):

Sub filterArrayX()
   Dim arr, dict As Object, El
   arr = Array(10, 10.5, 10.5, 10.5, 10.5)
   Set dict = CreateObject("Scripting.Dictionary")
   For Each El In arr
        If Not dict.Exists(El) Then
            dict.Add El, 1
        Else
            dict(El) = dict(El) + 1
        End If
   Next
   Debug.Print dict(10)   
   Debug.Print dict(10.5)
End Sub