2016-06-28 81 views
0

我構建了一個vlookup代碼,但似乎無法理解我做錯了什麼。我收到運行時錯誤'9':下標超出範圍錯誤消息。Vlookup運行時錯誤9

Cells(lrow + 1, 2) = Application.WorksheetFunction.vlookup(_ 
    Corp.Sheets("Sheet3").Range("$B$1"), _ 
    Workbooks("S:\_Shared Files MTL\Corporate Spreads\Weekly Sheets\" & _ 
       myvalue & "_weekly sheet.xls"). _ 
       Sheets("Pricing Sheet").Range("$B$18:$L$232"), 5, False) 

我想從其他工作簿中的數據拉到當前工作簿(Dim Corp)。

其他工作簿具有動態名稱和日期(myvalue)每週更改。

我要求用戶輸入一個消息框日期:

myvalue = InputBox("Insert date of file to upload in format yy_mm_dd", "User date", Format(Now(), "yy_mm_dd")) 

任何想法,爲什麼VLOOKUP公式不工作?

回答

1

您無法在Excel中未打開的工作簿上運行vlookup。您首先需要打開工作簿。

未經測試:

Sub Tester() 

    Const MY_PATH As String = "S:\_Shared Files MTL\Corporate Spreads\Weekly Sheets\" 

    Dim myValue, fName As String, wb As Workbook, v, sht As Worksheet 

    Set sht = ActiveSheet 

    myValue = InputBox("Insert date of file to upload in format yy_mm_dd", _ 
         "User date", Format(Now(), "yy_mm_dd")) 

    fName = myValue & "_weekly sheet.xls" 

    If Dir(MY_PATH & fName, vbNormal) <> "" Then 

     Set wb = Workbooks.Open(MY_PATH & fName, ReadOnly:=True) 

     v = Application.VLookup(Corp.Sheets("Sheet3").Range("$B$1"), _ 
       wb.Sheets("Pricing Sheet").Range("$B$18:$L$232"), 5, False) 

     sht.Cells(lrow + 1, 2) = IIf(IsError(v), "No match!", v) 

     wb.Close False 

    Else 
     MsgBox "no matching file found!" 
    End If 

End Sub