我从这里的另一个答案得到了这个代码,它比他们做的更好,因为你实际上只能选择你从哪里拉文件。但似乎我无法在VLOOKUP中获得完全正确的文件名?我在VLOOKUP之后收到错误1004。也许还有其他错误。我复制了这段代码然后替换了我需要的东西,但我还需要另外一双眼睛。提前谢谢。
Dim x As String
Dim lNewBracketLocation As Long
x = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose previous quarter's file", MultiSelect:=False)
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("V2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP($E2,'" & x & "]file_2017072732'!$B$5:$AP$9486,18,FALSE)"
' ERROR 1004
Selection.AutoFill Destination:=Range("V2:V177")
Range("V2:V177").Select
当我到达那一点时,它表明x等于"C:\Name\Name\Name\[Filename.xlsx"
。
这应该是格式吗?
答案 0 :(得分:2)
问题不在于x
的值,看起来它的格式有效。
问题在于使用A1
符号将使用FormulaR1C1
表示法编写的公式分配给单元格。
更改
ActiveCell.FormulaR1C1 = "=VLOOKUP($E2,'" & x & "]file_2017072732'!$B$5:$AP$9486,18,FALSE)"
到
ActiveCell.Formula = "=VLOOKUP($E2,'" & x & "]file_2017072732'!$B$5:$AP$9486,18,FALSE)"
或
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC5,'" & x & "]file_2017072732'!R5C2:R9486C42,18,FALSE)"
应该没问题。