使用带有选项参数的 UDF 进行输出计算。
注意事项:
功能 GetPercentage。根据传入的选项参数返回百分比。
Arg1:rng1 范围对象 1 例如单元格 A2
Arg2:rng2 范围对象 2 例如单元格 B2
Arg3:calcOption; "C" = 普通,"A" 是唯一的,"B" 是唯一的。
代码:
Option Explicit
Public Function GetPercentage(ByRef rng1 As Range, ByRef rng2 As Range, ByVal calcOption As String) As Double
Application.Volatile
'calcOption C = Common , A is a only, B is B only.
Dim arr1() As String, arr2() As String, totalAItems As Long, totalBItems As Long, totalItems As Long
arr1 = Split(rng1.Value, ",")
arr2 = Split(rng2.Value, ",")
totalAItems = GetDistinctCount(arr1)
totalBItems = GetDistinctCount(arr2)
totalItems = GetDistinctCount(Split(rng1.Value & "," & rng2.Value, ","))
Dim commonItemCount As Long
commonItemCount = GetSharedCount(arr1, arr2)
Select Case calcOption
Case "C"
GetPercentage = commonItemCount / totalItems
Case "A"
GetPercentage = OnlyInOneCell(arr1, arr2) / totalItems
Case "B"
GetPercentage = OnlyInOneCell(arr2, arr1) / totalItems
End Select
End Function
Public Function GetDistinctCount(ByVal arr As Variant) As Long
Dim tempDict As Object, i As Long
Set tempDict = CreateObject("Scripting.Dictionary")
For i = LBound(arr) To UBound(arr)
If Not tempDict.Exists(arr(i)) Then tempDict.Add arr(i), arr(i)
Next i
GetDistinctCount = tempDict.Count
End Function
Public Function GetSharedCount(ByVal arr1 As Variant, ByVal arr2 As Variant) As Long
Dim outCount As Long, i As Long
For i = LBound(arr1) To UBound(arr1)
If Not IsError(Application.Match(arr1(i), arr2, 0)) Then outCount = outCount + 1
Next i
GetSharedCount = outCount
End Function
Public Function OnlyInOneCell(ByVal arr1 As Variant, ByVal arr2 As Variant) As Long
Dim outCount As Long, i As Long, tempDict As Object
Set tempDict = CreateObject("Scripting.Dictionary")
For i = LBound(arr1) To UBound(arr1)
If IsError(Application.Match(arr1(i), arr2, 0)) Then
If Not tempDict.Exists(arr1(i)) Then tempDict.Add arr1(i), arr1(i)
End If
Next i
OnlyInOneCell = tempDict.Count
End Function
工作表中的 UDF