I have a problem with calling the Match function from a VBA code: it returns the wrong values.
I have a speadsheet like this (it’s an example):
a b c d
1 testRange testValue
2 01/01/2011 00:00 03/01/2011 00:00 testValue = A4
3 02/01/2011 00:00
4 03/01/2011 00:00 result from match function
5 04/01/2011 00:00 3 testResult = MATCH(C2,A2:A20,1)
6 05/01/2011 00:00
7 06/01/2011 00:00 testResult
8 07/01/2011 00:00 9
9 08/01/2011 00:00
10 09/01/2011 00:00
11 10/01/2011 00:00
12 11/01/2011 00:00
13 12/01/2011 00:00
14 13/01/2011 00:00
15 14/01/2011 00:00
16 15/01/2011 00:00
17 16/01/2011 00:00
18 17/01/2011 00:00
19 18/01/2011 00:00
20 19/01/2011 00:00
the range that I’m searching is in A1:A20, and I’m looking for the value wrote in C2, that as you can see is just a value of the range (this to be sure that the value is in the range). I expect the Match function to return the number 3, like it does when called from the spreadsheet (cell C5), but the function called in VBA returns the value 9 (cell C10). I used this code:
Sub testMatch()
testRange = Range("A2:A20")
testValue = Range("C2")
testResult = Application.WorksheetFunction.Match(testValue, testRange, 1)
Range("C8") = testResult
End Sub
I have already tried to cast testValue as Date and as Double (solutions suggested in other forums), but with Date I have the same result and with Double I get the Error 1004 “Unable to get the Match property of the WorksheetFunctions class”
Any suggestion?
Thanks
As suggested in other forums, you should type your variables (Date…) and use
Option Explicit.In this case, the error comes from the use of dates inside the
matchfunction, try this :(edit > source: thanks to this thread)
I’ve tested on your example and it works for me.
Regards,
Max