我是VBA新手,需要使用动态vlookup
执行lookup_value
。原因是实际的lookup_value列可以位于不同输入表的不同列索引上。
原始的vlookup公式如下所示:
"=VLOOKUP(C2,lookup!$A$2:$B$14,2,FALSE)" 'static vlookup
我想要完成的任务应该是这样的:
1)找到里面带有lookup_value的实际列索引(在上面的例子中它是C2)
With ws
Set FindRng = .Rows(1).Find(what:="Column Name") ' should be 3 for C
FiltCol = FindRng.Column ' get the column number where "Column Name" was found
End With
2)动态设置lookup_value(在本例中为C2)
Dim dynamic_lookup_value as Range
dynamic_lookup_value = ws.Cells(FiltCol, 2) ' should be column C cell 2
3)将lookup_value的动态引用设置为实际的vlookup公式(即,参考C2重新编写硬编码的C2 )
foobar = "=VLOOKUP(dynamic_lookup_value,lookup!$A$2:$B$14,2,FALSE)" 'dynamic vlookup
然而,(3)产生Run-time error '91' Object variable or With-block variable not set
。
如何使用VBA执行带有动态lookup_value的excel vlookup?
答案 0 :(得分:2)
首先,你在这里颠倒了列和行:
ws.Cells(FiltCol, 2)
应该是:
ws.Cells(2,FiltCol)
第二步你设定一个范围:
Set dynamic_lookup_value = ws.Cells(2,FiltCol)
然后,您不要将变量放在引号内,而是将它们与&
foobar = "=VLOOKUP(" & dynamic_lookup_value.Address(0,0) & ",lookup!$A$2:$B$14,2,FALSE)"
另一条建议:
FiltCol = FindRng.Column
如果找不到该值,则会出错。将它放在If语句中以检查是否找到了值:
If not FindRng is nothing Then
...
End IF