求助: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
相关产品推荐
相关产品推荐

