VBA中的Vlookup引用已关闭的工作簿

时间:2017-07-17 22:47:33

标签: excel vba excel-vba

我想创建一个以字符串作为输入的函数,在vlookup中使用此字符串作为参数从闭合的工作簿中获取值。

当数据和字符串都在同一工作表中时,以下代码有效:

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

简单地引用范围(如下面的代码)不起作用(我认为这是因为函数无法处理Workbooks.Open就像Subs)。

Set workbookVariable = Application.Workbooks.Open(path_to_file)

dataRange = workbookVariable.Sheets(1).Range("A1:B4")

我的表格(保存为'names.xls',保存在桌面中)如下所示:

           A       |        B
    1    Olivia    |       Spaghetti
    2    John      |       Steak
    3    Samuel    |       Rice
    4    Brian     |       Chicken

我想要一个函数调用,如:

= get_value(A1),这将返回A1中名称的食物。

如何调整我的代码,以便get_value也适用于其他工作簿?

1 个答案:

答案 0 :(得分:0)

Function auto_open()

Workbooks.Open ("C:\Users\bmartin598\desktop\name")

Workbooks("Book2").Activate 
'make this match the workbook this code is in

End Function



Function get_value(inputString As String)

Dim dataRange As Range

Dim workbookVariable As Workbook

Dim strVal As Variant

Set workbookVariable = Workbooks("name") 'change to match workbook name

Set dataRange = workbookVariable.Sheets(1).Range("A1:B4")

strVal = Workbooks("name").Sheets("Sheet1").Range(inputString).Value 
'make sure workbooks matches the name of your workbook

get_value = WorksheetFunction.VLookup(strVal, dataRange, 2, False)


End Function

Function auto_close()
Workbooks("name").Close
End Function

您可以将其用作解决方法。只要打开另一个工作簿并将其置于后台,它就会自动打开它。当您关闭工作簿时,您正在关闭参考工作簿。

希望这有帮助。

相关问题