如何将文件名插入VLOOKUP函数

时间:2015-10-23 13:43:48

标签: vba excel-vba filepath vlookup excel

我差不多完成了这个允许用户选择文件路径的宏,然后它将从另一个文件中的选定文件中执行vlookup。到目前为止我的代码看起来像:

Sub SelectFile()
Dim x As String
Dim lNewBracketLocation As Long

x = Application.GetOpenFilename()

MsgBox "You selected " & x
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(x, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
x = Left$(x, lNewBracketLocation) & "[" & Right$(x, Len(x) - lNewBracketLocation)

Range("AA2").FormulaR1C1 = "=VLOOKUP(RC[-1]C23&R[-1]C24,'" & x & "]Access'!C3:C27,6,0)"

选择文件后,VLOOKUP将需要如下所示:

  

= VLOOKUP($ W2& $ X2,'S:\财务预测\库存文件夹\ 2015 \ LW [08-AUG-Access Export.xlsx]访问'!$ C:$ AA,6,FALSE)

当我运行宏时,我不断得到运行时错误'1004':VLOOKUP公式行上的应用程序定义或对象定义错误 我是VBA的新手,非常感谢任何帮助。

此致 路加

1 个答案:

答案 0 :(得分:0)

你的公式中有太多的Cs。它应该是:

Range("AA2").FormulaR1C1 = "=VLOOKUP(R[-1]C23&R[-1]C24,'" & x & "]Access'!C3:C27,6,0)"

而不是

Range("AA2").FormulaR1C1 = "=VLOOKUP(RC[-1]C23&R[-1]C24,'" & x & "]Access'!C3:C27,6,0)"