[英]Excel VlookUp left cell into VBA from another workbook
Hi everybody, my VLookUp function is working so far, now I would like to convert it into a VBA function. 大家好,我的VLookUp函数到目前为止工作,现在我想将它转换为VBA函数。
My VLookUp: 我的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. 现在我想把它变成一个可以被调用的VBA函数。 So if the function is called "A6" sould be "overwriten" by the left cell of where the function has been called. 因此,如果函数被称为“A6”,则可以通过调用函数的左侧单元格“覆盖”。
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. 对不起,mabye不清楚。 "test.xls" is another workbook. “test.xls”是另一本工作簿。 The code should run inside the file called (eg) "missing.xls". 代码应该在名为(missing)“missing.xls”的文件中运行。
There are two methods. 有两种方法。
.formula
方法1:使用.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
方法2:使用.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. 因此, Application.Caller
获取函数所在的单元格,然后从那里可以使用该单元格的Offset
执行VLOOKUP()
。
EDIT 编辑
For this lookup to work test.xls
needs to be open. 要使这个查找工作test.xls
需要打开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.