简体   繁体   中英

Vlookup worksheet function in VBA (runtime error 9)

I'm new to VBA and I have the following code for a function :

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 .

The problem is that I get a runtime error 9. When I click Debug the following line gets highlighted :

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:

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:

在此处输入图片说明

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.

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