vba 通过组合 2 列形成唯一键的 VLOOKUP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21392307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VLOOKUP by Combining 2 Columns to Form a Unique Key
提问by jmaz
For the following table,
对于下表,
I want to look up the value in col C. Since the values in col A and col B are not unique, VLOOKUP fails. For example, VLOOKUP(1,table,3) returns 5 and never 1.
我想查找 col C 中的值。由于 col A 和 col B 中的值不是唯一的,因此 VLOOKUP 失败。例如,VLOOKUP(1,table,3) 返回 5 而从不返回 1。
However, the combinationsof cols A & B are unique. For example, 1blah = 5, while 1foo = 1.
但是,cols A 和 B的组合是唯一的。例如,1blah = 5,而 1foo = 1。
How can I use the combination of cols A & B as a unique key to return the corresponding value in col C?
如何使用 cols A & B 的组合作为唯一键来返回 col C 中的相应值?
I'm not sure if this should be implemented with worksheet functions or a custom VBA function. I tried using CONCATENATE to generate the unique key, but this did not work because this results in combinations of numbers and strings.
我不确定这是否应该使用工作表函数或自定义 VBA 函数来实现。我尝试使用 CONCATENATE 生成唯一键,但这不起作用,因为这会导致数字和字符串的组合。
采纳答案by Dmitry Pavliv
You can use an array formula:
您可以使用数组公式:
=INDEX($C:$C,MATCH("1foo",$A:$A & $B:$B,0))
just select in example D1
, enter formula in formula bar and press CTRL+SHIFT+ENTERto evaluate it
只需在示例中选择,D1
在公式栏中输入公式,然后按CTRL+ SHIFT+ENTER对其进行评估
回答by Tmdean
The way I usually do it is by concatenating the values separated by a pipe character (|). See the formula in the screenshot below.
我通常这样做的方法是连接由管道字符 (|) 分隔的值。请参阅下面屏幕截图中的公式。
Then you can vlookup using the concatenated key.
然后您可以使用连接的键进行 vlookup。
=VLOOKUP("1|foo",$C:$D,2,FALSE)
回答by AgentGG
You can use VLOOKUP if your lookup value is a concatenation of your two or more key fields (A2&B2). Then, add a first sorted column in your LUT sheet with the array that is the concatenation of the same key fields. Viola.
如果查找值是两个或多个关键字段 (A2&B2) 的串联,则可以使用 VLOOKUP。然后,在 LUT 表中添加第一个已排序的列,其中的数组是相同关键字段的串联。中提琴。