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

求助:Application.Match在VBA数组中处理日期时无法正常工作

VBA中Application.Match查找Date数组返回错误2042的解决方法

你遇到的问题是Application.Match在匹配VBA原生Date类型数组时返回错误2042,这是因为该函数是Excel工作表函数的封装,内部将日期识别为双精度浮点数,而VBA的Date是独立数据类型,导致类型匹配失败。

以下是三种可行的解决方法:

方法1:将查找日期转为双精度浮点数

把要匹配的Date值通过CDbl()转换为Excel日期的存储格式(双精度浮点数),再执行匹配:

Dim MyDate As Date
MyDate = #12/15/2024#

Dim SomeDates(1 To 3) As Date
SomeDates(1) = #12/6/2024#
SomeDates(2) = #12/15/2024#
SomeDates(3) = #12/22/2024#

Debug.Print Application.Match(CDbl(MyDate), SomeDates, 0) ' 返回2

方法2:使用Variant数组替代Date数组

将存储日期的数组定义为Variant类型,而非Date类型,让Application.Match能正确识别日期值:

Dim MyDate As Date
MyDate = #12/15/2024#

Dim SomeDates(1 To 3) As Variant
SomeDates(1) = #12/6/2024#
SomeDates(2) = #12/15/2024#
SomeDates(3) = #12/22/2024#

Debug.Print Application.Match(MyDate, SomeDates, 0) ' 返回2

方法3:使用VBA原生循环匹配

如果不想依赖Excel工作表函数,直接用VBA循环遍历数组查找目标日期:

Dim MyDate As Date
MyDate = #12/15/2024#

Dim SomeDates(1 To 3) As Date
SomeDates(1) = #12/6/2024#
SomeDates(2) = #12/15/2024#
SomeDates(3) = #12/22/2024#

Dim idx As Integer
For idx = LBound(SomeDates) To UBound(SomeDates)
    If SomeDates(idx) = MyDate Then
        Debug.Print idx ' 返回2
        Exit For
    End If
Next idx

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 03:26:07