I want to create a function that takes a string as input, use this string as argument in a vlookup to get a value from a closed workbook.
The following code works when the data and the string are both in the same worksheet:
Function get_value(inputString as String)
Dim dataRange as Range
Set dataRange = Range("A1:B4")
get_value = Application.WorksheetFunction.Vlookup(inputString, dataRange, 2, False)
End Function
Simply referencing the range (like the code below) doesn't work (I assumed that this is because Functions can't handle Workbooks.Open like Subs).
Set workbookVariable = Application.Workbooks.Open(path_to_file)
dataRange = workbookVariable.Sheets(1).Range("A1:B4")
My table (saved as 'names.xls', saved in Desktop) looks like:
A | B
1 Olivia | Spaghetti
2 John | Steak
3 Samuel | Rice
4 Brian | Chicken
I want want a function call like:
=get_value(A1) and that will return the food of the name in A1.
How can I adjust my code so get_value works on other workbooks too ?
Thisworkbook.Path & Application.PathSeparator & Range("A1:B4").Address(External:=true)
. You may need parts of it and setup Connection to that workbook. – PatricK