使用Excel VBA计算不同的值

时间:2017-05-19 11:11:06

标签: excel vba excel-vba

我有这个代码来计算不同的值,但我只需要查看可见范围和过滤范围

Public Function CountDistinct(dataRange As Range) As Long
    'Populate range into array
    If dataRange.Rows.Count < 2 Then
        ReDim varTemp(1 To 1, 1 To 1)
        varTemp(1, 1) = dataRange
    Else
        varTemp = dataRange
    End If

    'Dictionaries can be used to store unique keys into memory
    Set dictTemp = New Dictionary

    'Add array items into dictionary if they do not exist
    For lngCounter = LBound(varTemp) To UBound(varTemp)
        If dictTemp.Exists(varTemp(lngCounter, 1)) = False Then
            dictTemp.Add Key:=varTemp(lngCounter, 1), Item:=1
        End If
    Next lngCounter

    'Count of unique items in dictionary
    CountDistinct = dictTemp.Count
End Function

1 个答案:

答案 0 :(得分:1)

这是Mr. Excel

的功能
Function CountUniqueVisible(Target As Range)
''==============================================
''Return the # of unique items in visible cells in a selected range
''Created 29 July 2011 by Denis Wright
''==============================================
Dim Rng As Range, _
    c As Range
Dim dic As Object
Dim y
Dim j As Long
Dim Sht As Worksheet
Dim strSheets As String

Set dic = CreateObject("Scripting.Dictionary")
Set Rng = Target.SpecialCells(xlCellTypeVisible)
j = 0
For Each c In Rng
    If Not dic.exists(c.Value) Then
        j = j + 1
        dic.Add c.Value, j
    End If
Next c
y = dic.keys
'Now we have a list of unique values. Next step is to return the count.
CountUniqueVisible = UBound(y) + 1

ExitHere:
    Set dic = Nothing
    Set Rng = Nothing
End Function

这可用作VBA函数,而不是UDF工作表函数。