I am trying to call a function in Excel in one file using a vlookup from another file. The code works correctly if I am using it from the sheet that has the lookup table. However, when I run it from another file, I usually get a #Value error. Until I am using the source file for other things. Then it magically works in the background. Until I click on it and then it goes back to #Value. Here is the top of the function from VBA:
'Requires the correct workbook to work
Function testFunction(body As String)
'open the source file (didn't work)
'Dim location As String
'location = "C:\Users\moish\OneDrive\Documents\space flight.xlsx"
'Dim book As Workbook
Dim sheet As Worksheet
'Set book = Workbooks.Open(location)
'Set sheet = book.Sheets("Bodies")
Set sheet = ActiveWorkbook.Sheets("Bodies")
'clean up input
Dim rng As Range
Dim matchValue, matchType
Set rng = ActiveSheet.Range("A2:A221")
'try exact match
matchValue = Application.match(body, rng, 0)
If Not Application.IsNA(matchValue) Then
matchType = "Exact"
testFunction = WorksheetFunction.VLookup(body, sheet.Range("A1:J221"), 2, False)
End If
End Function
The rest of it shouldn't matter to the problem. Usage: =testFunction("Jupiter")
UPDATE: This works if I open the correct file manually and just leave it in the background. I am not sure why it needs to be coded this way though and I cannot figure out how to get it to open the correct file automatically.
Dim sheet As Worksheet
Workbooks("space flight.xlsx").Worksheets("Bodies").Activate
Set sheet = Workbooks("space flight.xlsx").Worksheets("Bodies")
Application.match(body, rng, 0)? where isbodydefined ?Set rng = ActiveSheet.Range("A2:A221")? Why ActiveSheet and notActiveWorkbook.Sheets("sheetname")?