如何应用错误值为 0 的 vlookup 并恢复

How to apply vlookup with on error value 0 and resume

我正在使用 vlookup 范围在最后一个空列中应用公式。 它工作正常,但如果出现错误,它会显示空白单元格,嗯,我不介意,但是, 当在下一列中再次应用该公式时,该值将转移到前一列的空白单元格,因为前一列中的一个单元格由于错误而为空白。

所以我需要它给出值 0 或 "error" 而不是空白。

Sub GET_BHAV()

    Dim OpenWs As Worksheet, bhavWs As Worksheet
    Dim OpenLastRow As Long, bhavLastRow As Long, x As Long
    Dim bhavRng As Range

    Set OpenWs = ThisWorkbook.Worksheets("Open")

    Workbooks.Open "C:\Users\playt\Desktop\STACK\VANGU\cm07JAN2020bhav.csv"

    Set bhavWs = Workbooks("cm07JAN2020bhav.csv").Worksheets("cm07JAN2020bhav")

    bhavLastRow = bhavWs.Range("A" & Rows.Count).End(xlUp).Row
    OpenLastRow = OpenWs.Range("A" & Rows.Count).End(xlUp).Row

    Set bhavRng = bhavWs.Range("A2:G" & bhavLastRow)

    For x = 2 To OpenLastRow
        On Error Resume Next
        OpenWs.Cells(x, Columns.Count).End(xlToLeft).Offset(0, 1).Value = Application.WorksheetFunction.VLookup( _
                                                                          OpenWs.Range("A" & x).Value, bhavRng, 3, Flase)
    Next x

End Sub

您需要捕获(处理)VLOOKUP 错误,以防找不到匹配项。

尝试下面 VLOOKUP 部分的代码:

' define a new variable
Dim VlookUpVal As Variant

With OpenWs ' Using With statement
    For x = 2 To OpenLastRow
        ' read the value of VLOOKUP to variant
        VlookUpVal = Application.VLookup(.Range("A" & x).Value, bhavRng, 3, False)

        ' check if VLOOKUP returned an Error
        If IsError(VlookUpVal) Then
            .Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 1).Value = 0
        Else
            .Cells(x, .Columns.Count).End(xlToLeft).Offset(0, 1).Value = VlookUpVal
        End If
    Next x
End With