简体   繁体   English

VBA 中的 Vlookup 工作表函数(运行时错误 9)

[英]Vlookup worksheet function in VBA (runtime error 9)

I'm new to VBA and I have the following code for a function :我是 VBA 新手,我有以下函数代码:

Function checktype(ByVal modele As String)

Dim srchRange As Range
Dim book1 As Workbook

'Set some Workbook variables:
Set book1 = Workbooks("C:\Users\MZ\Desktop\EPI.xlsx")


Set srchRange = book1.Sheets(1).Range("A1:D800")

'This assumes that the Book2 is Open and you are on the desired active worksheet:
checktype = Application.WorksheetFunction.VLookup(modele, srchRange, 4, False)


End Function

The aim of this code is to get a certain number from another workbook using Vlookup function and return the value to the function checktype .此代码的目的是使用 Vlookup 函数从另一个工作簿中获取某个数字,并将该值返回给函数checktype

The problem is that I get a runtime error 9. When I click Debug the following line gets highlighted :问题是我收到运行时错误 9。当我单击 Debug 时,以下行会突出显示:

Set book1 = Workbooks("C:\Users\MZ\Desktop\EPI.xlsx")

Either make sure that the workbook is opened in the same instance of excel and refer it like this:要么确保工作簿在一个 excel实例中打开,并像这样引用它:

Set book1 = Workbooks("C:\Users\MZ\Desktop\EPI.xlsx")
Set book1 = Workbooks("EPI.xlsx") 'specifying only the name is OK as well

or或者

Set book1 = Workbooks.Open("C:\Users\MZ\Desktop\EPI.xlsx")

An example of 2 Excel files in the same instance:同一实例中的 2 个 Excel 文件的示例:

在此处输入图片说明

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

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