简体   繁体   English

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

[英]VBA/Excel: Get cell from different sheet

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!提前致谢!

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?如前所述,VLOOKUP 是最简单和最快的方法,但我假设您不希望在该单元格或整个 Sheet1 上有公式? Here is one simple way to do the same in VBA while still using a VLOOKUP - just not on 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.使用 Sheet2!Z1 进行计算,如果您的工作簿中使用了该单元格,则只需使用隐藏区域中的任何其他未使用单元格。 Formula in Sheet2!Z1 : Sheet2!Z1 中的公式:

=VLOOKUP(Sheet1!$A$1,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 保持干净的公式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM