使用Excel VBA计算不同的值
我有这段代码来计算不同的值,但我需要它只查看可见范围和过滤器范围使用Excel VBA计算不同的值,vba,excel,Vba,Excel,我有这段代码来计算不同的值,但我需要它只查看可见范围和过滤器范围 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
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
Public Function CountDistinct(dataRange作为Range)尽可能长
'将范围填充到数组中
如果dataRange.Rows.Count<2,则
ReDim varTemp(1到1,1到1)
varTemp(1,1)=数据范围
其他的
varTemp=dataRange
如果结束
'字典可用于将唯一键存储到内存中
Set dictTemp=新字典
'如果数组项不存在,则将其添加到字典中
对于lngCounter=LBound(varTemp)到UBound(varTemp)
如果dictTemp.存在(varTemp(lngCounter,1))=False,则
dictTemp.Add键:=varTemp(lngCounter,1),项:=1
如果结束
下一个lngCounter
'字典中唯一项的计数
CountDistinct=dictTemp.Count
端函数
这是一个用于此目的的函数,来自:
这是一个VBA函数,而不是UDF工作表函数。的可能重复项
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