唯一计数(Excel VBA vs 公式)更快的方法

Unique Count (Excel VBA vs Formulas) Faster Approach

32 位 Excel 64 位 Win7 上的 365 工作表 300600 行 x 105 列 目标:计算每列中唯一条目的数量

尝试的解决方案 1:公式

{=SUM(1/COUNTIF(A8:A300600,A8:A300600))}

问题:运行时间长,冻结 Excel,必须停止计算

尝试的解决方案 2:VBA UDF

Function UniqueCount(Selection As Range) As Integer
Dim UniqueArray()
ReDim UniqueArray(0 To Selection.Count)
Dim Rng As Range
Dim CUniqueCount As Integer
CUniqueCount = 0
For Each Rng In Selection
    For i = 0 To Selection.Count
        If UniqueArray(i) = Rng.Value Then Exit For
        If UniqueArray(i) = "" Then
            UniqueArray(i) = Rng.Value
            CUniqueCount = CUniqueCount + 1
            Exit For
        End If
    Next i
Next
UniqueCount = CUniqueCount
End Function

注意:这要快得多,但我仍在寻找更快的方法

试试这个

'Set a reference to MS Scripting runtime ('Microsoft Scripting Runtime')
Function UniqueCount(SelRange As Range)
    Dim Rng As Range
    Dim dict As New Scripting.Dictionary
    Set dict = CreateObject("Scripting.Dictionary")
    For Each Rng In SelRange
        If Not dict.Exists(Rng.Value) Then
            dict.Add Rng.Value, 0
        End If
    Next Rng
    UniqueCount = dict.Count
    Set dict = Nothing
End Function

我会使用数组和字典:

Public Function CountUnique(rngInput As Range) As Double
    Dim rngCell               As Range
    Dim dData                 As Object
    Dim vData
    Dim x                     As Long
    Dim y                     As Long

    Set dData = CreateObject("Scripting.Dictionary")

    vData = rngInput.Value2
    For x = LBound(vData, 1) To UBound(vData, 1)
        For y = LBound(vData, 2) To UBound(vData, 2)
            If LenB(vData(x, y)) <> 0 Then dData(CStr(vData(x, y))) = Empty
        Next y
    Next x
    CountUnique = dData.Count
End Function