VBA Vlookup使用VLookup查找值

时间:2019-03-20 00:50:12

标签: excel vba

我正在尝试创建一个宏,该宏遍历工作表中名为“源”的每一行。它需要在命名范围“ OverheadResults”中寻找匹配值。

我测试时得到

  

错误1004“对象'_Worksheet'的方法'范围'失败

当我尝试使用vlookup时(向下滚动到“ Main”循环中)

Private Const SOURCE_SHEETNAME = "source"
Private Const COLUMN_WBS = 2
Private Const COLUMN_COSTELEM = 9
Private Const COLUMN_COST = 12
Private Const COLUMN_HOURS = 15
Private Const OVERHEAD_LOOKUP_RANGE_NAME = "OverheadResults"

Sub ConvertSAPActuals()
    Dim iLastRow As Long
    Dim iDestRow As Long
    Dim wb As Workbook
    Dim wbDest As Workbook
    Dim shtSource As Worksheet
    Dim shtDest As Worksheet
    Dim sCostElem As String
    Dim result As Variant


    '--make sure source sheet exists
    If Not SheetExists(SOURCE_SHEETNAME) Then
        MsgBox "Missing source sheet", vbCritical
        Exit Sub
    End If

    Set wb = ThisWorkbook
    Set shtSource = wb.Sheets(SOURCE_SHEETNAME)

    '--create destination workbook and sheet
    Set wbDest = Workbooks.Add
    Set shtDest = wbDest.Sheets(1)

   '--Find the last row (in column A) with data.
    iLastRow = shtSource.Range("A:A").Find("*", searchdirection:=xlPrevious).Row

    '--Main Loop
    iDestRow = 1
    For iSourceSheetRow = 2 To iLastRow
        sCostElem = shtSource.Cells(iSourceSheetRow, COLUMN_COSTELEM)
        result = Application.WorksheetFunction.VLookup(sCostElem, shtSource.Range(OVERHEAD_LOOKUP_RANGE_NAME), 2, False)

        '--Check return value of Vlookup
        If IsError(result) Then
        Else
        End If

    Next

End Sub

2 个答案:

答案 0 :(得分:1)

虽然看起来违反直觉,但是您无法捕获Application.WorksheetFunction.VLookup或WorksheetFunction.VLookup抛出的工作表错误(例如,#N / A,#REF!等),成为使用IsError检查的变体。 / p>

您需要改用Application.VLookup。

    Dim result As Variant

    '...

    result = Application.VLookup(sCostElem, shtSource.Range(OVERHEAD_LOOKUP_RANGE_NAME), 2, False)

    '--Check return value of Vlookup
    If IsError(result) Then
        debug.print "error: " & result
    Else
        debug.print "match: " & result
    End If

答案 1 :(得分:0)

轻微错误处理

如果您不想更改代码,可以使用以下代码:

    On Error Resume Next
    result = Application.WorksheetFunction.VLookup(sCostElem, _
            shtSource.Range(OVERHEAD_LOOKUP_RANGE_NAME), 2, False)
    '--Check return value of Vlookup
    If Err Then
        ' Reset error.
        On Error GoTo 0
      Else
'***********************************************************
    ' IMPORTANT CORRECTION:
    ' Added the following line for reasons Pᴇʜ pointed out in the comments.
        ' Reset error.
        On Error GoTo 0
'***********************************************************
        ' Do stuff with 'result' e.g.
        Debug.Print result
    End If