[英]How to use Vlookup in vba
I am trying to use vlookup through VBA to fetch values across two different workbooks (A,B) and fill some values in a column of workbook A 我正在尝试通过VBA使用vlookup在两个不同的工作簿(A,B)中获取值,并在工作簿A的列中填充一些值
The important requirment for me is that the search range in workbook B should be dynamic. 对我来说,重要的要求是工作簿B中的搜索范围应该是动态的。
Therefore I have already calculated the number of rows of the table in workbook B. 因此,我已经计算了工作簿B中表的行数。
Here is the code I tried to write.It does not compile due to the syntax error inside the Vlookup: 这是我尝试编写的代码,由于Vlookup内部的语法错误而无法编译:
ActiveWorkbook.Sheets("Sheet1").Activate
Columns("M:M").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("M2").Select
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-12],[petest.xlsx]Sheet1!A1:"&lrow2,8,FALSE),RC[-1])"
Range("M2").Select
Selection.AutoFill Destination:=Range("M2:M" & lrow)
Range("M2:M" & lrow).Select
Here lrow contains the last column of the table of the first workbook while lrow2 the last column in the second workbook ( the one I am searching into) 这里的lrow包含第一个工作簿的表的最后一列,而lrow2包含第二个工作簿的表的最后一列(我正在搜索的那个)
Try changing this line : 尝试更改此行:
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-12],[petest.xlsx]Sheet1!A1:"&lrow2,8,FALSE),RC[-1])"
to 至
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(RC[-12],[petest.xlsx]Sheet1!A1:L" & lrow & ",8,FALSE),RC[-1])"
This will insert the actual value of lrow into the formula 这会将row的实际值插入公式中
UPDATE UPDATE
You need to add "L" to the vlookup formula so it has A1:L and not just A1. 您需要在vlookup公式中添加“ L”,以便它具有A1:L而不只是A1。 I have edited the code above.
我已经编辑了上面的代码。 Try that please
请尝试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.