You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建电子表格函数:按年份和地点筛选后返回非数值型众数?

自定义函数:按年份和地点筛选后返回频次最高的员工姓名

需求说明

现有一份员工工作记录表格:

  • A列:日期(Dates)
  • B列:地点(Locations)
  • C列:姓名(Names)

需要创建一个函数,接收年份和地点作为输入参数,筛选出对应年份、对应地点的记录后,返回C列中出现频次最高的姓名。

示例数据

DatesLocationsNames
01/01/2020New YorkBart
01/02/2020New YorkBart
01/03/2020ChicagoKate
01/04/2020ChicagoKate
01/05/2020ChicagoJohn
01/01/2022SeattleKate
01/02/2022SeattleMark
01/03/2022New YorkBart
01/04/2022SeattleMark
01/05/2022New YorkBart
01/06/2022New YorkKate

调用示例

  • =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版本)

  1. 按下Alt+F11打开VBA编辑器;
  2. 右键当前工作簿 → 插入 → 模块;
  3. 粘贴以下代码:
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
  1. 返回工作表,直接调用函数即可,比如=MostFrequentName(2022, "Seattle")会返回Mark。

内容的提问来源于stack exchange,提问作者C418chick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 08:25:34