views:

142

answers:

2

Data in TheRange is {1,"",1,"",1,"",1,"",2}

=Match(2, TheRange, 1) returns 9 as expected

=Match(1.5, TheRange, 1) returns 7 as expected

=Match(1, TheRange, 1) returns 5 which is not expected

Anyone come across this ? Anyone got a fix?

Additionally if I use Worksheet.Function.Match in VBA I get more unexpected results.

+3  A: 

If you specify 1 for the "match_type" argument (the 3rd argument to MATCH), then Excel expects the array to be sorted. Apparently, Excel does a binary search for the value - starting in the middle and finding the middle value (which is the 5th value in your case) when searching for 1.

If you specify 0 for "match_type", you will get what you expect - at least for this case. See the documentation for the MATCH function for more info.

Joe Erickson
The challenge to me is that it doesn't work on a sparce array for the third case but does for the first two cases. I'd be happier to get an error back for all three cases rather than the inconsistent behaviour of sometimes navigating a sparce array and sometimes not.
DangerMouse
But Excel isn't making you any guarantees about what it will do when the array isn't sorted and you tell Excel the array *is* sorted...
jtolle
The array is sorted but sparce. Many of Excel's functions work fine with a sparce array, e.g. Sum, StDev, etc and match generally does just not in some very specific sets (see above) of ordered sparce data. It looks like inconsistent behaviour to me that there is no fix for other than to write my own implementation.
DangerMouse
I don't think Excel really has any concept of a sparse array. In Excel the number 1 (or any number) is less than the empty string (or any string). The array just isn't sorted as far as Excel is concerned, so you should expect erratic behavior from a binary search.
jtolle
A: 

One way to solve this is turn the blanks to errors.

Try these formula:

=MATCH(1/(2),1/$A$1:$A$9,-1)
=MATCH(1/(1.5),1/$A$1:$A$9,-1)
=MATCH(1/(1),1/$A$1:$A$9,-1)

These are array formulas so when you type them in you must confirm them with "ctrl+shift+enter" instead of just "enter".

Dan