简体   繁体   中英

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. Later on down the line, the user creates a second workbook (let's call it B), which is assigned another variable. 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. 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:

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

Where 'B' is the variable name.

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.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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