Hi everybody, my VLookUp function is working so far, now I would like to convert it into a VBA function.
My VLookUp:
=VLOOKUP(A6;'[test.xls]Sheet1'!$A:$B;2;0) 'example for Cell A6, which can vary
Now I would like to get this into a VBA function which can be called. So if the function is called "A6" sould be "overwriten" by the left cell of where the function has been called.
I have tried following code:
Sub lookup()
Dim x1 As String
x1 = ActiveCell.Offset(0, -1).Select
VLOOKUP(x1,'[test.xls]Sheet1'!$A:$B;2;0)
End Sub
What is necessary that it's working as expected?
I'm grateful for any tips.
Sorry, mabye it wasn't clear. "test.xls" is another workbook. The code should run inside the file called (eg) "missing.xls".
There are two methods.
.formula
sub method1()
dim x1 as range
set x1 = ActiveCell.Offset(0, -1)
x1.formula = "=VLOOKUP(A6,'[test.xls]Sheet1'!$A:$B,2,0)"
end sub
.value
sub method2()
dim x1 as range
set x1 = activecell.offset(0, -1)
x1.value = application.vlookup(range("A6").value, workbooks("test.xls").worksheets("Sheet1").range("A:B"),2,0)
end sub
This one should do it:
Function MyLookup()
Dim source As Workbook
Dim current As Range
Set current = Application.Caller
Set source = Workbooks("test.xls")
MyLookup = Application.WorksheetFunction.VLookup(current.Offset(0, -1).Value, source.Sheets(1).Range("A:B"), 2, False)
End Function
So Application.Caller
gets the cell where the function is located and from there you can perform VLOOKUP()
with Offset
from that cell.
EDIT
For this lookup to work test.xls
needs to be open.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.