0
votes

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!

2

2 Answers

1
votes

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.

1
votes

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)"