简体   繁体   English

使用VBA在Excel中引用变量工作簿

[英]Referencing variable workbooks in Excel using VBA

I have a scenario where a user creates a workbook, then this workbook (let's call it A) is assigned a variable. 我有一个场景,用户创建一个工作簿,然后为该工作簿(我们称其为A)分配一个变量。 Later on down the line, the user creates a second workbook (let's call it B), which is assigned another variable. 接下来,用户创建第二个工作簿(我们称其为B),并为其分配了另一个变量。 The names of these workbooks are not fixed, thus they are always variables. 这些工作簿的名称不是固定的,因此它们始终是变量。

Now I want to do a VLOOKUP in Workbook A of a value contained in Workbook B using VBA. 现在,我想使用VBA在工作簿A中对工作簿B中包含的值进行VLOOKUP。 Is this possible? 这可能吗? If so, what would the code look like? 如果是这样,代码将是什么样?

Here's my attempt at this, which didn't go over too well with Excel: 这是我的尝试,在Excel中并没有很好地解决:

Range("X7").Formula = "=VLOOKUP(K7,[B]Sheet1!$A:$B,2,FALSE)" Range(“ X7”)。Formula =“ = VLOOKUP(K7,[B] Sheet1!$ A:$ B,2,FALSE)”

Where 'B' is the variable name. 其中“ B”是变量名。

Thanks! 谢谢!

I would do: 我会做:

oCell.Formula = "VLOOKUP(" & oKeyCell.Address & ", " & oSearchRange.Address(External:=True) & ", 2, FALSE)"

In other words, rather than calculating what the address is in code, let Excel do it. 换句话说,而不是计算代码中的地址,而是让Excel执行。

Your solution is good except you forgot one thing: 您的解决方案是好的,除了您忘记了一件事:

"=VLOOKUP(K7,[" & Book "]Sheet1!$A:$B,2,FALSE)"

You need an extra & sign after the Book : 你需要一个额外的&后签Book

"=VLOOKUP(K7,[" & Book & "]Sheet1!$A:$B,2,FALSE)"

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

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