繁体   English   中英

Excel VlookUp将单元格从另一个工作簿中保留到VBA中

[英]Excel VlookUp left cell into VBA from another workbook

大家好,我的VLookUp函数到目前为止工作,现在我想将它转换为VBA函数。

我的VLookUp:

=VLOOKUP(A6;'[test.xls]Sheet1'!$A:$B;2;0) 'example for Cell A6, which can vary

现在我想把它变成一个可以被调用的VBA函数。 因此,如果函数被称为“A6”,则可以通过调用函数的左侧单元格“覆盖”。

我试过以下代码:

Sub lookup()
        Dim x1 As String
        x1 = ActiveCell.Offset(0, -1).Select
        VLOOKUP(x1,'[test.xls]Sheet1'!$A:$B;2;0)
End Sub

它有什么必要按预期工作?

我很感激任何提示。


更新:

对不起,mabye不清楚。 “test.xls”是另一本工作簿。 代码应该在名为(missing)“missing.xls”的文件中运行。

有两种方法。

方法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

方法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

这个应该这样做:

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

因此, Application.Caller获取函数所在的单元格,然后从那里可以使用该单元格的Offset执行VLOOKUP()

编辑

要使这个查找工作test.xls需要打开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM