简体   繁体   中英

VBA vlookup formula refering another opened workbook

I am trying to add a vlookup formula by using VBA, however, it didn't work for me. It's refering to another workbook and the workbook's name is save in a variable called FileName1. Below are the code I wrote. Could any one please help?

WbkT3.Worksheets("Finance").Range("G2") = "=VLOOKUP(C2,[" & FileName1 & "]Divisor!$A:$F,3,FALSE)"

The vlookup formula is not 100% correct. The range should refer to something like $B$3:$C$5. Add the missing row references, and the formula should work.

How excel is interpreting the file name is the most probable cause of the problem.

Try this. Remove the square brackets from the formula replace with single quotes. Add teh square brackets to the file name variable if possible. Code below was tested and works.

Dim FileName1 As String
FileName1 = "C:\temp\[Book2.xlsx]"

ActiveWorkbook.Worksheets("Sheet1").Range("G2")  = "=VLOOKUP(C2,'" & FileName1 & "Sheet1'!$B$3:$C$5,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