I try to do a Vlookup in a closed workbook via ExecuteExcel4Macro. Since I need to find a lot of values in different workbooks it makes sense to do it in a closed workbook.
I used the below code, but it doesn't work if I enter the function on my Excel book:
=GetVlookup("D:", "testfile.xls", "Sheet1", "C1:D8", 2, "CDM-01_10")
I can assure that there is a file on my D: named testfile.xls with a sheet1 and content in the range I mention here. But result is #value!.
I want this in a function since I want to make a price calculation add-in that can be used in several workbooks, so I rather haven't introduced this in a macro.
Public Function GetVlookup(path, file, sheet, ref, Col, vVal)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetVlookup = "File Not Found"
Exit Function
End If
If IsNumeric(vVal) Then
vVal = CDbl(vVal)
Else
vVal = Chr(34) & vVal & Chr(34)
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & Range(ref).Address(, , xlR1C1)
' Execute an XLM macro
GetVlookup = ExecuteExcel4Macro("Vlookup(" & vVal & "," & arg & "," & Col & ",0)")
End Function