JenniferMurphy
Well-known Member
- Joined
- Jul 23, 2011
- Messages
- 2,369
- Office Version
- 365
- Platform
- Windows
I was having trouble getting the Match and Lookup function to work, so I put them in a UDF. It has a simple syntax and does not require that the lookup list be sorted. Here's the code. Please let me know if there is a better way.
Here's a simple table.
<tbody>
</tbody>
And here's the UDF in action.
<tbody>
</tbody>
Code:
' My LookUp Function
' Look up (search for) a value in one list and return the corresponding value in another.
' The lists must be one-dimensional (vectors), but either one can be vertical or horizontal.
' The comparison is not case sensitive ("abc" = "ABC" = "aBc"),
' but it does respect spaces ("abc" <> "a bc" <> " abc" <> "abc ").
' This function does what the built-in LookUp function should have done.
' It works the same way, but does not require that LookupVector be sorted.
' Syntax: =MyLookUp(LookupValue, LookupVector, ResultVector)
' LookupValue The value to be looked up in the Lookup vector.
' LookupVector The vector (row or column) where the LookupValue will be searched for.
' ResultVector The vector where the corresponding value will be found and returned.
Function MyLookUp(LookupValue, LookupVector, ResultVector)
Dim LookupIndex
LookupIndex = WorksheetFunction.Match(LookupValue, LookupVector, False) 'Find the first match
MyLookUp = WorksheetFunction.index(ResultVector, LookupIndex) 'Find the corresponding value
End Function
Here's a simple table.
R/C | C | D |
4 | Month | Sales |
5 | Jan | $8,141 |
6 | Feb | $2,647 |
7 | Mar | $5,211 |
8 | Apr | $4,825 |
9 | May | $7,225 |
10 | Jun | $9,031 |
<tbody>
</tbody>
And here's the UDF in action.
R/C | K | L | M | N |
4 | Month | Sales | Formula | Comments |
5 | may | $7,225 | L5: =mylookup(K5,C5:C10,D5:D10) | Lower case |
6 | FEB | $2,647 | L6: =mylookup(K6,C6:C11,D6:D11) | Upper case |
7 | Apr | $4,825 | L7: =mylookup(K7,C7:C12,D7:D12) | Mixed case |
8 | jum | #VALUE! | L8: =mylookup(K8,C8:C13,D8:D13) | Misspelled |
9 | Mar | #VALUE! | L9: =mylookup(K9,C9:C14,D9:D14) | Trailing space |
10 | Jul | #VALUE! | L10: =mylookup(K10,C10:C15,D10:D15) | Missing value |
<tbody>
</tbody>