I would like to modify this function : Custom Excel VBA Function (Modified VLOOKUP) from Cell referring to a range in different file gives an error
functionality I need is conceptualy simple – I need VlookUp which return value that corresponds to k-th occurance of lookup value instead of standard 1-th, example :
If k-th occurance doesn’t exist then function should return an error.
Spreadsheet-like data :
A B
1 "a" "1a"
2 "a" "2a"
3 "b" "1b"
4 "a" "3a"
5 "b" "2a"
VLOOKUPnew(lookup_value =A1, table_array =A1:B3,
col_index_num = 2, exactMatch =0, k=1) should return 1a
VLOOKUPnew(lookup_value =A1, table_array =A1:B3,
col_index_num = 2, exactMatch =0, k=2) should return 2a
VLOOKUPnew(lookup_value =A1, table_array =A1:B3,
col_index_num = 2, exactMatch =0, k=3) should return 3a
VLOOKUPnew(lookup_value =A3, table_array =A1:B3,
col_index_num = 2, exactMatch =0, k=1) should return 1b
VLOOKUPnew(lookup_value =A3, table_array =A1:B3,
col_index_num = 2, exactMatch =0, k=2) should return 2b
VLOOKUPnew(lookup_value =A3, table_array =A1:B3,
col_index_num = 2, exactMatch =0, k=3) should return error
I’m familiar with R and Matlab, so my thinking is vector oriented, I’ve first tried to write code for case witk k=1 or 2 by rewriting one line of code (from post I’m linking to) :
row = .Match(lookup_value, table_array.Columns(1), 0)
into :
If k =2 Then
row_1 = .Match(lookup_value, table_array.Columns(1), 0)
number_of_rows=table_array.Columns(1).Rows.Count
row = .Match(lookup_value, table_array.Columns(1).Rows( (row_1+1):number_of_rows ), 0)
above line is pseudocode because I don’t have any idea how to write it properly (.Rows( (row_1+1):number_of_rows ) is vector of numbers and it looks quite funny)
else
row = .Match(lookup_value, table_array.Columns(1), 0)
End If
for k > 2 it would be simple (but inefficient) to put this code into for loop.
I’ve noticed that modified .Match() which takes also k as parameter would make all job needed. Using loop for to find position of k-th occurance of value seems to be quite slow or mayby I’m just not very familiar with VBA.
You may try out both of these Excel based formula: Adjust according to your data table.
CountIFfunction allows you to count number of occurances of a lookup value in a column range.=COUNTIF(columnRange,lookupvalue)Assume this is what you may be looking for: Data extracted from the reference.
CUSTcolumn is populated using=F78&COUNTIF($F$75:$F78,F78)Final nth Lookup:
e.g. Phonenumber for 4th occurance for Customer =
Smith=VLOOKUP($D$74&"4",$G$75:$H$93,2,FALSE)Reference from Chandoo: 4. Lookup 2nd / 3rd / 4th occurrence of an item in a list.
Sample data used for following formula:
Formula:
Reference from CPearson Arbitary Lookups.
Personally I don’t fancy volatile functions such as
index()…though..