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

Excel自定义SumName函数调用报错求助:工作表调用返回值错误

问题分析与修复方案

核心错误点

  1. 未处理查找为空的场景:当目标人员缩写在查找区域中不存在时,nameFind会变成Nothing,此时执行firstFind = nameFind.Address会直接触发运行时错误。
  2. 变量未声明:firstFind、Cell_called、Cell_found未显式声明,属于隐式变体变量,容易引发类型不匹配问题。
  3. 单元格引用未限定工作表:Range(myCol & myRow)默认引用当前活动工作表,若查找区域和调用单元格不在同一张表,会导致数据引用错误。
  4. 调用单元格参数冗余易出错:手动传递Caller参数容易输入错误,改用Application.Caller可自动获取调用单元格信息,无需手动传参。

修复后的代码

Option Explicit ' 强制变量声明,避免隐式错误

Public Function SumName(shortName As String, lookupRange As Range) As Double
    Dim Days As Double
    Dim nameFind As Range
    Dim firstFind As String
    Dim targetCol As String
    Dim ws As Worksheet
    
    Application.Volatile
    
    Days = 0
    Set ws = lookupRange.Parent ' 获取查找区域所在的工作表
    
    ' 直接获取调用单元格的列字母
    targetCol = Split(ws.Cells(1, Application.Caller.Column).Address, "$")(1)
    
    With lookupRange
        ' 首次查找目标人员缩写
        Set nameFind = .Find(What:=shortName, _
                            LookAt:=xlWhole, _
                            MatchCase:=False, _
                            SearchFormat:=False)
                            
        ' 仅找到匹配项时执行循环汇总
        If Not nameFind Is Nothing Then
            firstFind = nameFind.Address
            Do
                ' 累加对应列的天数,限定在查找区域所在工作表
                Days = Days + ws.Range(targetCol & nameFind.Row).Value
                
                ' 查找下一个匹配项
                Set nameFind = .FindNext(nameFind)
                
                ' 回到首个匹配项时退出循环
                If nameFind.Address = firstFind Then Exit Do
            Loop While Not nameFind Is Nothing
        End If
    End With
    
    SumName = Days
End Function

使用说明

在工作表单元格中调用时,仅需传入两个参数:

=SumName("人员缩写", $B$5:$B$20)
  • "人员缩写":要统计的目标人员缩写
  • $B$5:$B$20:存储所有人员缩写的查找区域(对应你表中下部的B列范围)

函数会自动识别调用单元格所在的列,汇总该列下所有匹配人员的工作天数。

替代方案(无需VBA)

如果周数列连续且人员缩写固定在B列,可直接用Excel内置函数组合实现,更稳定易维护:

=SUMIF($B$5:$B$20, "人员缩写", C$5:C$20)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:45:40