【问题标题】:Count distinct values with Excel VBA使用 Excel VBA 计算不同的值
【发布时间】:2017-05-19 11:11:05
【问题描述】:

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

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

【问题讨论】:

标签: vba excel


【解决方案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 工作表函数。

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多