我想计算包含下拉列表中的多个选择的列中唯一选择的数量。
例如,B3 列包含,
星期一星期二星期三
count 函数返回的值为 1,而不是 3 - 有没有办法可以分别计算这三天?谢谢!
使用以下 VBA 代码可以从下拉列表中进行多项选择:https://docs.google.com/document/d/1JU7G_Tna2zPBtcG2TlarxKCTbuinNsg5LwBqzmuJYK8/edit
答案1
最简单的解决方案是使用 UDF。(我甚至不确定使用标准公式是否可行。)
工作表设置如下:
将以下代码复制粘贴到标准模块:
'============================================================================================
' Module : <any standard module>
' Version : 0.1.1
' Part : 1 of 1
' References : (Optional) Microsoft Scripting Runtime [Scripting]
' Source : https://superuser.com/a/1332369/763880
'============================================================================================
Option Explicit
Public Function CountDistintMultiSelections _
( _
count_array As Range _
) _
As Long
Dim dictSelections As Object '##Early Bound## As Scripting.Dictionary
Set dictSelections = CreateObject("Scripting.Dictionary") '##Early Bound## = New Dictionary
Dim celCell As Range
For Each celCell In Intersect(count_array, count_array.Parent.UsedRange)
Dim varSelections As Variant
varSelections = Split(celCell.Value2, ", ")
Dim varSelection As Variant
For Each varSelection In varSelections
If dictSelections.Exists(varSelection) Then
dictSelections(varSelection) = dictSelections(varSelection) + 1
Else
dictSelections.Add varSelection, 1
End If
Next varSelection
Next celCell
CountDistintMultiSelections = dictSelections.Count
End Function
在中输入以下公式C2
:
=CountDistintMultiSelections(B:B)
解释:
代码使用函数Split()
分离每个单元格中的各个选择,并使用字典来计算唯一的选择。
笔记:
要安装 UDF,请按照下列步骤操作:
- 按Alt+F11
- 选择菜单项
Insert
→Module
- 将代码粘贴到主窗口中