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

Excel VBA如何正确传递不同工作表的Range至自定义函数?

问题分析与解决方案

嘿,这问题我太熟了!你遇到的错误确实是因为没有明确指定单元格所属的工作表导致的。

问题根源

你的代码里有这一行:

If Cells(dt.Row, dt.Column + 1).Value = client Then

这里的Cells默认会指向当前活动工作表的单元格,但dt是来自Diff_sheet的区域,当你在其他工作表调用公式时,Cells就会去当前工作表找对应行/列的单元格,而不是Diff_sheet里的,自然匹配不到正确的客户数据,返回错误。

修正后的代码

只需要给Cells加上工作表归属,用dt.Parent获取dt所在的工作表即可:

Function LastDayForClient(client As String, mnth As Integer, dates As Range) As String
    Dim dtRow As Date
    Dim dt As Range
    dtRow = 0
    
    For Each dt In dates
        ' 如果不是目标月份,跳过
        If Month(dt.Value) = mnth Then
            ' 用dt.Parent指定工作表,确保取到对应区域的客户名称
            If dt.Parent.Cells(dt.Row, dt.Column + 1).Value = client Then
                If dtRow = 0 Then
                    dtRow = dt.Value
                ElseIf dtRow < dt.Value Then
                    dtRow = dt.Value
                End If
            End If
        End If
    Next dt
    
    LastDayForClient = Format(dtRow, "dd.mm.yyyy")
End Function

关键修改点

  • dt.Parent:表示dt这个单元格所属的工作表对象,不管dates参数来自哪个工作表,都能精准定位到同一工作表里的相邻列数据,不再依赖活动工作表。

现在你再用这个公式:

=LastDayForClient("Client_name";5;Diff_sheet!G6:G297)

跨工作表引用就能正常返回结果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:24:48