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

问题描述 投票:1回答:1

我希望从一个工作簿到另一个工作簿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

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

真的很感激帮助。谢谢。

excel vba excel-vba
1个回答
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,但它可以正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.