工作簿之间的Vlookup在VBA中不起作用

时间:2018-04-10 09:03:59

标签: excel vba excel-vba

我希望从一个工作簿到另一个工作簿vlookup一个数据透视表,但是我收到以下错误:

enter image description here

源工作簿看起来像这样(Sheet Piv_Repos):

enter image description here

目标工作簿看起来像这样(Sheet Nominator):

enter image description here

这是我的代码:

Dim sourceBook3 As Workbook
Dim Srepfile3 As String
    MsgBox ("Select Adjusted data")
    Srepfile3 = Application.GetOpenFilename
    Set sourceBook3 = Application.Workbooks.Open(Srepfile3, UpdateLinks:=0)
Dim sourcesheet As Worksheet
Set sourcesheet = sourceBook3.Sheets("Piv_Repos")

Dim destSheet1 As Worksheet
Set destSheet1 = ThisWorkbook.Sheets("Nominator")

Dim lastrow As Long

lastrow = destSheet1.Range("B" & Rows.Count).End(xlUp).Row

Set myrange = sourcesheet.Range("A:B")

For i = 35 To lastrow
destSheet1.Cells(i, 8) = Application.WorksheetFunction.VLookup(destSheet1.Cells(i, 2), myrange, 2, False)

Next I

当我在其他工作簿之间使用它时,这个看似精确的代码工作正常。

真的很感激帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

问题出在WorksheetFunction,而不是两本工作簿中。

尝试一些小到这些:

Option Explicit

Sub TestMeWS()

    Dim myRange As Range
    Set myRange = Worksheets(1).Range("A:B")
    Debug.Print Application.WorksheetFunction.VLookup("something", myRange, 2, 0)

End Sub


Sub TestMeAPP()

    Dim myRange As Range
    Set myRange = Worksheets(1).Range("A:B")
    Debug.Print Application.VLookup("something", myRange, 2, 0)

End Sub

你会注意到,如果"某事"在myRange中不存在,您在1004中收到TestMeWS错误。在第二种情况下,您可以在即时窗口中获得error 2042,但它可以正常工作。