I have a custom worksheet function which will perform a vlookup from an external Excel file. The specific external file will depend on the parameters passed to the function.
The simplified code below works great as long as the external file is open.
It does not work if the external file is not already open. From watching the locals window, I can see that the myBook object gets set to the *current* file. What would cause the workbooks.open(myFile) to return the current file instead of the correct external file?
The simplified code below works great as long as the external file is open.
It does not work if the external file is not already open. From watching the locals window, I can see that the myBook object gets set to the *current* file. What would cause the workbooks.open(myFile) to return the current file instead of the correct external file?
Code:
Function JGLookup(myFile As String, myLookup As String)
On Error GoTo errorLine
Dim myBook As Workbook
Dim mySheet As Worksheet
Dim myRange As Range
myPath = "C:\lookup\"
Set myBook = Workbooks.Open(myFile & myPath, 0, True) '<---- This is where I have the problem
Set mySheet = myBook.Sheets(1)
Set myRange = mySheet.Range("$A$2:$P$10000")
myAnswer = Application.WorksheetFunction.VLookup(myLookup, myRange, 9, False)
JGLookup = myAnswer
Set myBook = Nothing
errorLine:
laborStat = Error$
Set myBook = Nothing
End Function