I am trying to create a macro which includes a VLOOKUP but the VLOOKUP file would change each time. I would like the reference file in the VLOOKUP to be a variable. Ideally the macro would prompt the user to choose a file they wish to VLOOKUP from. So far I have this but it doesn't seem to be working...("test" is what the worksheet is named).
Sub VLOOKUP()
Application.ScreenUpdating = False
Dim myFilename As String
MsgBox "Please choose file with name to use in VLOOKUP formula.", vbOKOnly, "Choose file"
myFilename = CStr(Application.GetOpenFilename)
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'[" & myFilename & "]test'!C9:C10,2,0)"
End Sub
However, the VLOOKUP in the cell is not showing up how it should. e.g.
=VLOOKUP(B12,'[G:\OPS\National Pricing Data And Risk\Vehicle Pricing\VP Work\Gareth\Even Newer Toyota Macro Test\[Z401 Toyota Test COMPLETE.xlsx]test]Z401 Toyota Test COMPLETE.xlsx]'!$I:$J,2,0)
I'm not sure where the extra ]Z401 Toyota Test COMPLETE.xlsx] is coming from. Is there something I'm missing/not doing correctly?
Edit:
Sub VLOOKUP()
Application.ScreenUpdating = False
Dim fullPath As String
Dim tmpName As String
Dim tmpPath As String
Dim myFilename As String
fullPath = "G:\OPS\National Pricing Data And Risk\Calculators, Docs, Templates & Guides\Toyota Macros.xlsm"
tmpName = fso.GetFileName(fullPath)
tmpPath = fso.GetParentFolderName(fullPath)
myFilename = tmpPath & "\[" & tmpName & "]"
Range("M12").FormulaR1C1 = "=VLOOKUP(RC[-11],'[" & myFilename & "]test'!C9:C10,2,0)"
End Sub