Использование UDF с дополнительным параметром для расчета выхода.
Примечания:
Функция GetPercentage
.Возвращает процент в соответствии с переданным аргументом опции.
Arg1 : rng1
объект диапазона 1, например, ячейка A2
Arg2 : * диапазон 1020 *объект 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в листе