简体   繁体   English

vlookup错误处理,错误2042

[英]vlookup error handling, error 2042

I'm trying to get a Vlookup working in VBA, and I have this code: 我正在尝试在VBA中使用Vlookup ,并且我有以下代码:

Dim Result As Variant

    For i = 2 To lastrow
        Result = Application.VLookup(Template.Range("A" & i).Value2, EDM.Range("B:BP"), 5, False)
        If IsError(Result) Then
            Template.Range("E" & i).Value2 = ""
        Else
            Template.Range("E" & i).Value2 = Result
        End If
    Next i

For some reason every cell is coming up blank. 由于某种原因,每个单元格都变成空白。 If I manually type the formula in a cell with a match it works fine. 如果我在具有匹配项的单元格中手动键入公式,则效果很好。 I'm guessing it has something to do with the error handling, maybe? 我猜想它与错误处理有关,也许吗? The goal is to look up the value in Template, column A against EDM column B and return EDM Column G. 目的是对照EDM列B在Template的A列中查找值,并返回EDM列G。

You are right, it is related to your Error Handling, you need to trap the VLookup error a bit differently, by using If IsError(Application.VLookup...) . 你是对的,它关系到你的错误处理,你需要捕获VLookup错误有点不同,通过使用If IsError(Application.VLookup...)

Note : in your post you wrote you are looking to compare "against EDM column B", in your code you wrote EDM.Range("B:BP") , so which one is it? 注意 :在您的文章中,您正在编写“ EDM列B”对比;在代码中,您编写了EDM.Range("B:BP") ,那是哪一个?

Try the code below : 试试下面的代码:

Dim Result As Variant

For i = 2 To lastrow
    If IsError(Application.VLookup(Template.Range("A" & i).Value2, EDM.Range("B:BP"), 6, False)) Then
        Template.Range("E" & i).Value2 = ""
    Else
        Result = Application.VLookup(Template.Range("A" & i).Value2, EDM.Range("B:BP"), 6, False)
        Template.Range("E" & i).Value2 = Result
    End If
Next i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM