首页 > 解决方案 > 从不同文件引用的 Vlookup

问题描述

试图从不同的文件中查找,其中一个文件在不同的文件夹中,我得到 o 作为查找输出,。我需要查找接近 100,000 行,我该怎么做,查找结果是一个字符串,但是当我将 myvlookupresult 声明为字符串时,代码运行但没有输出。有人可以帮忙吗

Private Sub VLookup2()
On Error Resume Next
    Dim myLookupValue As String
    Dim myFirstColumn As Long
    Dim myLastColumn As Long
    Dim myColumnIndex As Long
    Dim myFirstRow As Long
    Dim myLastRow As Long
    Dim myVLookupResult As Long
    Dim myTableArray As Range
    Set wb1 = Workbooks("COCO PILOT MTS_2612").Sheets("Sheet1")

    myLookupValue = wb1.Range("B").Value
    myFirstColumn = 1
    myLastColumn = 3
    myColumnIndex = 3
    myFirstRow = 2
    myLastRow = 500

    With Workbooks("master zonal head lsit.xlsx").Worksheets("Sheet1")
        Set myTableArray = .Range(.Cells(myFirstRow, myFirstColumn), .Cells(myLastRow, myLastColumn))
    End With

     myVLookupResult = WorksheetFunction.VLookup(myLookupValue, myTableArray, myColumnIndex, False)
    Range("C").Value = myVLookupResult

End Sub

标签: excelvbavlookup

解决方案


首先,以下几行是不正确的......

myLookupValue = wb1.Range("B").Value

Range("C").Value = myVLookupResult

您省略了行引用。所以它应该是这样的......

myLookupValue = wb1.Range("B2").Value

Range("C2").Value = myVLookupResult

其次,您On Error Resume Next在代码的开头有。这将隐藏所有错误。如果要使用它,则需要正确处理。但是,在这种情况下,不需要使用它来处理 VLookup() 返回的错误。

WorksheetFunction.VLookup()我们可以使用 ,而不是使用Application.VLookup()。这样,当没有匹配时会发生非破坏性IsError()错误,我们可以使用. 这是一个例子......

Dim myVLookupResult As Variant

myVLookupResult = Application.VLookup(myLookupValue, myTableArray, myColumnIndex, False)

If Not IsError(myVLookupResult) Then
    Range("C2").Value = myVLookupResult
Else
    Range("C2").Value = "N/A"
End If

请注意,myVLookupResult 被声明为 Variant,因为除了字符串之外,VLookup() 还可以返回错误。

编辑

要在一系列单元格中输入公式,然后将公式转换为值,请尝试以下操作...

With Range("C2:C" & myLastRow)
    .Formula = "=VLOOKUP(B2," & myTableArray.Address(external:=True) & "," & myColumnIndex & ",0)"
    .Value = .Value
End With

希望这可以帮助!


推荐阅读