vba 如何仅对过滤后的数据/可见单元格应用 vlookup 公式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40247140/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:25:01  来源:igfitidea点击:

how to apply vlookup formula on filtered data/visible cells only

vbaexcel-vbaexcel

提问by Prakash

I have filtered column "A" and i need to apply vlookup formula on the visible cells in column "A". How do i achieve this in vba . number of total rows in the worksheet are 30,000 and the filtered rows are closed to 100.

我已经过滤了“A”列,我需要在“A”列中的可见单元格上应用 vlookup 公式。我如何在 vba 中实现这一点。工作表中的总行数为 30,000,过滤后的行数接近 100。

回答by LoHer

You could solve this problem without VBA, just with an Excel array formula.
But if you wish to set this formula with VBA, just use the Range.FormulaArrayproperty.

您可以在没有 VBA 的情况下解决此问题,只需使用 Excel 数组公式即可。
但是如果你想用 VBA 设置这个公式,只需使用Range.FormulaArray属性。

We are using this array formula:

我们正在使用这个数组公式:

{=VLOOKUP(A2,IF(SUBTOTAL(3,OFFSET(Table2!$B:$B,ROW(Table2!$B:$B)-ROW(Table2!$B),0,1)),Table2!$B:$C,0),2,0)}

To use it in Excel you need to paste it without the enclosing curly brackets and press ctrl+ shift+ enter(Windows) or cmd+ shift+ enter(Mac) to activate the array formula.

要在 Excel 中使用它,您需要粘贴它而不使用大括号,然后按ctrl+ shift+ enter(Windows) 或cmd+ shift+ enter(Mac) 激活数组公式。



How does the formula work?

公式是如何工作的?

The data sheet Table2looks like this:

数据表Table2如下所示:

  Column A    Column B    Column C
┌  ─  ─  ─  ┬  ─  ─  ─  ┬  ─  ─  ─  ┐
│   Month   │   Store   │  Revenue  │
├  ─  ─  ─  ┼  ─  ─  ─  ┼  ─  ─  ─  ┤
│    Jan    │     1     │   6.000   │
├  ─  ─  ─  ┼  ─  ─  ─  ┼  ─  ─  ─  ┤
│    Jan    │     2     │   8.000   │
├  ─  ─  ─  ┼  ─  ─  ─  ┼  ─  ─  ─  ┤
│    Feb    │     1     │  10.000   │
├  ─  ─  ─  ┼  ─  ─  ─  ┼  ─  ─  ─  ┤
│    Feb    │     2     │  12.000   │
└  ─  ─  ─  ┴  ─  ─  ─  ┴  ─  ─  ─  ┘

The data sheet is filtered by month, so that February is visible only.
The result will be look like this:

数据表按月份过滤,因此只有二月可见。
结果将如下所示:

  Column A    Column B
┌  ─  ─  ─  ┬  ─  ─  ─  ┐
│   Store   │  Revenue  │
├  ─  ─  ─  ┼  ─  ─  ─  ┤
│     1     │   10.000  │ Formula: {=VLOOKUP(A2,IF(SUBTOTAL(3,OFFSET(Table2!$B:$B,ROW(Table2!$B:$B)-ROW(Table2!$B),0,1)),Table2!$B:$C,0),2,0)}
├  ─  ─  ─  ┼  ─  ─  ─  ┤
│     2     │   12.000  │ Formula: {=VLOOKUP(A3,IF(SUBTOTAL(3,OFFSET(Table2!$B:$B,ROW(Table2!$B:$B)-ROW(Table2!$B),0,1)),Table2!$B:$C,0),2,0)}
└  ─  ─  ─  ┴  ─  ─  ─  ┘

My answer is based on this solution.

我的回答是基于这个解决方案