我想修改这个函数:来自单元格的自定义 Excel VBA 函数(修改后的 VLOOKUP)引用不同文件中的范围会给出错误
我需要的功能在概念上很简单 - 我需要 VlookUp 它的返回值对应于查找值的第 k 次出现而不是标准的第 1 次,例如:
如果第 k 次出现不存在,则函数应返回错误。
类似电子表格的数据:
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
我熟悉 R 和 Matlab,所以我的想法是面向向量的,我首先尝试通过重写一行代码(来自我链接到的帖子)来编写 case witk k=1 或 2的代码:
row = .Match(lookup_value, table_array.Columns(1), 0)
进入 :
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)
上面的行是伪代码,因为我不知道如何正确编写它(.Rows( (row_1+1):number_of_rows )
是数字向量,看起来很有趣)
else
row = .Match(lookup_value, table_array.Columns(1), 0)
End If
对于 k > 2,将此代码放入 for 循环会很简单(但效率低下)。
我注意到修改后的 .Match() 也将k作为参数,这将使所有工作都需要。使用循环来查找第 k 个值出现的位置似乎很慢,或者我可能对 VBA 不太熟悉。