简体   繁体   English

VB中的VLookup返回错误2042,其中工作表中的VLookup返回预期值

[英]VLookup in VB returning Error 2042 where VLookup in worksheet returns expected

I'm trying to write a function that will lookup a value in a table based on a matching date. 我正在尝试编写一个函数,该函数将基于匹配日期在表中查找值。 In the event of no match it will lookup up to 7 days prior before returning an error. 如果没有匹配,它将在返回错误之前最多7天进行查找。

Option Explicit
Public Function GetWeekEndBalanceFromStatement(lookupDate As Date, statement As Range, column As Integer) As Variant
    Dim lookupModifier As Integer

    Do While IsError(Application.VLookup(DateAdd("d", lookupModifier, lookupDate), statement, column, False)) And lookupModifier > -7
        lookupModifier = lookupModifier - 1
    Loop

    GetWeekEndBalanceFromStatement = Application.VLookup(DateAdd("d", lookupModifier, lookupDate), statement, column, False)
End Function

The issue I'm having when I break it down for debugging is the VLookups consistently return 分解调试时遇到的问题是VLookups始终返回

Error 2042 错误2042

even in the event an identical VLookup written in the spreadsheet returns a value. 即使在电子表格中写入了相同的VLookup也会返回一个值。

The written function calls for reference, K8 being the first line: 编写的函数需要参考,K8是第一行:

=DATE(2018,1,5)
=VLOOKUP(K8, A:F, 6,FALSE )
=GetWeekEndBalanceFromStatement(K8,A:F,6)

Any clues as to what I may be doing wrong? 关于我可能做错了什么的任何线索? I've attempted encapsulating dates in CDate, appending .Value to ranges and bringing in date as a variant and accessing .Value2. 我试图将日期封装在CDate中,将.Value附加到范围中,然后将日期作为一个变量引入并访问.Value2。

After running some tests, I recall some issues I faced when using VLookup and Match with Dates, better use their Excel values (change Date to Double ). 运行一些测试后,我记得使用VLookup和“与日期Match时遇到的一些问题,最好使用它们的Excel值(将Date更改为Double )。

Modified Function Code 修改功能码

Option Explicit

Public Function GetWeekEndBalanceFromStatement(lookupDate As Double, statement As Range, column As Integer) As Variant
    Dim lookupModifier As Integer

    Do While IsError(Application.VLookup(lookupDate + lookupModifier, statement, column, False)) And lookupModifier > -7
        lookupModifier = lookupModifier - 1
    Loop

    GetWeekEndBalanceFromStatement = Application.VLookup(lookupDate + lookupModifier, statement, column, False)
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM