如何创建电子表格函数:按年份和地点筛选后返回非数值型众数?
自定义函数:按年份和地点筛选后返回频次最高的员工姓名
需求说明
现有一份员工工作记录表格:
- A列:日期(Dates)
- B列:地点(Locations)
- C列:姓名(Names)
需要创建一个函数,接收年份和地点作为输入参数,筛选出对应年份、对应地点的记录后,返回C列中出现频次最高的姓名。
示例数据
| Dates | Locations | Names |
|---|---|---|
| 01/01/2020 | New York | Bart |
| 01/02/2020 | New York | Bart |
| 01/03/2020 | Chicago | Kate |
| 01/04/2020 | Chicago | Kate |
| 01/05/2020 | Chicago | John |
| 01/01/2022 | Seattle | Kate |
| 01/02/2022 | Seattle | Mark |
| 01/03/2022 | New York | Bart |
| 01/04/2022 | Seattle | Mark |
| 01/05/2022 | New York | Bart |
| 01/06/2022 | New York | Kate |
调用示例
=MostFrequentName(2020, "Chicago")返回 Kate=MostFrequentName(2022, "New York")返回 Bart
解决方案
方案1:Excel内置函数组合(无需VBA,适用于Excel 365/2021)
用FILTER+MODE.SNGL组合实现,公式如下:
=MODE.SNGL(FILTER(C:C, (YEAR(A:A)=年份参数)*(B:B=地点参数), ""))
- 逻辑:
FILTER先筛选出符合条件的姓名列表,MODE.SNGL返回列表中频次最高的第一个值; - 若存在多个频次相同的最高值,可改用
MODE.MULT返回所有结果。
方案2:VBA自定义函数(兼容所有Excel版本)
- 按下
Alt+F11打开VBA编辑器; - 右键当前工作簿 → 插入 → 模块;
- 粘贴以下代码:
Function MostFrequentName(targetYear As Integer, targetLocation As String) As String Dim ws As Worksheet Dim lastRow As Long Dim nameCounts As Object Dim i As Long Dim currentName As String Dim maxCount As Integer Dim resultName As String ' 指定数据所在工作表,可修改为Sheets("你的工作表名") Set ws = ActiveSheet lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row Set nameCounts = CreateObject("Scripting.Dictionary") ' 遍历数据行(假设第1行是表头) For i = 2 To lastRow If Year(ws.Cells(i, "A").Value) = targetYear And ws.Cells(i, "B").Value = targetLocation Then currentName = ws.Cells(i, "C").Value ' 统计姓名出现次数 If nameCounts.Exists(currentName) Then nameCounts(currentName) = nameCounts(currentName) + 1 Else nameCounts.Add currentName, 1 End If End If Next i ' 找出频次最高的姓名 maxCount = 0 resultName = "" For Each key In nameCounts.Keys If nameCounts(key) > maxCount Then maxCount = nameCounts(key) resultName = key End If Next key MostFrequentName = resultName End Function
- 返回工作表,直接调用函数即可,比如
=MostFrequentName(2022, "Seattle")会返回Mark。
内容的提问来源于stack exchange,提问作者C418chick
相关产品推荐
相关产品推荐

