2

I need to apply MATCH function to a range of dates (in VBA. The standard MATCH function written as cell formula does work as intended.) looking for the largest possible index whose corresponding date is <= the looked-up date. Here's my code and a minimum working example:

Function test_debug_func(x As Date, arr As Range) As Integer
Debug.Print "entered function"
test_debug_func = WorksheetFunction.Match(x, arr, 1)

End Function

enter image description here

And I checked that the function is indeed entered by printing the debug statement. However, it cannot proceed with the WorksheetFunction.Match function. I also checked that all dates are indeed Date and not other formats.

It simply doesn't make any sense to me why this wouldn't work. Could anyone kindly help? Thanks!

1 Answer 1

3

Since dates are just numbers, you can use CLng:

test_debug_func = WorksheetFunction.Match(CLng(x), arr, 1)
Sign up to request clarification or add additional context in comments.

2 Comments

Wow, thanks it works! But it's strange that I also tried Cint and it didn't work. Also, I would expect Excel to be smart enough to implicitly convert Date to Integer when comparing them, but it didn't...
The maximum value of an Integer is 32767... your dates correspond to larger numbers, e.g. 2020/1/1 is 43831, so you need CLng instead of CInt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.