VBA/Excel:从不同的工作表获取单元格

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

VBA/Excel: Get cell from different sheet

excelvbafindcell

提问by Splendid Lobster

Long story short: I have two sheets in Excel: Sheet1 which has two cells (A1 & A2) and Sheet2 (providing some data) which looks like this:

长话短说:我在 Excel 中有两张工作表:Sheet1 有两个单元格(A1 和 A2)和 Sheet2(提供一些数据),如下所示:

  | A | B  |
--|---|----|
1 | a | 5  |
2 | b | 10 |
3 | c | 15 |
4 | ...

So here's my problem: in Sheet1 when I enter "b" in A1 it should automatically enter 10 in A2.

所以这是我的问题:在 Sheet1 中,当我在 A1 中输入“b”时,它应该自动在 A2 中输入 10。

Kinda like a simple find operation which will return the cell (or column) number and use that to return the value for the cell right next to it. But how do I do this?

有点像一个简单的查找操作,它将返回单元格(或列)号并使用它来返回它旁边单元格的值。但是我该怎么做呢?

Thanks in advance!

提前致谢!

回答by MarcoK

As mentioned before, a VLOOKUP is the simplest and fastest way but I assume you do not want to have a formula in that cell or on that whole Sheet1 for that matter? Here is one simple way to do the same in VBA while still using a VLOOKUP - just not on Sheet1:

如前所述,VLOOKUP 是最简单和最快的方法,但我假设您不希望在该单元格或整个 Sheet1 上有公式?这是在仍然使用 VLOOKUP 的同时在 VBA 中执行相同操作的一种简单方法 - 只是不在 Sheet1 上:

Use Sheet2!Z1 for calculation, if that cell is used in your workbook, just use any other unused cell in an area that is hidded for example. Formula in Sheet2!Z1 :

使用 Sheet2!Z1 进行计算,如果您的工作簿中使用了该单元格,则只需使用隐藏区域中的任何其他未使用单元格。Sheet2!Z1 中的公式:

=VLOOKUP(Sheet1!$A,Sheet2!$A$B,2,FALSE)

Simple VBA to populate Sheet1!A2:

简单的 VBA 来填充 Sheet1!A2:

sum DoIt
  Worksheets("Sheet1").Range("A2").Value = Worksheets("Sheet2").Range("Z1").Value
  end sub

You can call the DoIt sub with a button for example and it will keep your Sheet1 / cell A2 clean of formulas.

例如,您可以使用一个按钮调用 DoIt 子程序,它将使您的 Sheet1/单元格 A2 保持干净的公式。