【问题标题】:How can I input same value in place of Vlookup `#N/A`如何输入相同的值来代替 Vlookup `#N/A`
【发布时间】:2021-05-22 06:07:29
【问题描述】:

我想更新其简短形式的端口代码。假设我有端口代码DMM。我VLOOKUP 这个单元格反对SADMM。这意味着如果我输入DMM,我将得到SADMM。但是如果我没有DMM,它将显示#N/A。而不是这个我想要DMM;如果VLOOKUP 找不到该值,则为原始值。

代码

Sub Vlookup_POD()
    On Error Resume Next
    
    Dim rng As Range, FinalResult As Variant, Table_Range As Range, LookupValue As Range

    Set rng = Sheets("Sheet3").Range(Range("I14"), Range("I14").End(xlDown))

    Set Table_Range = Sheets("Pod").Range("A1:B25")

    Set LookupValue = Sheets("Sheet3").Range(Range("I14"), Range("I14").End(xlDown))
    'Range ("I14:I500")

    FinalResult = Application.WorksheetFunction.VLookup(LookupValue, Table_Range, 2, False)
    rng = FinalResult
End Sub

【问题讨论】:

    标签: excel vba vlookup


    【解决方案1】:

    我通常使用IsError() 来捕获这类错误。这是一个例子。

    FinalResult = Application.VLookup(LookupValue, Table_Range, 2, False)
    
    If IsError(FinalResult) Then FinalResult = LookupValue
    
    rng.Value = FinalResult
    

    注意:如果我想捕获特定错误,我会使用CVERR()

    还有一个提示。避免不必要地使用On Error Resume Next。仅在需要时使用它。或者更好的是,进行正确的错误处理。

    【讨论】:

    • 您还可以通过使用“vba 字典”执行查找以指数方式提高代码的性能。虽然有时很有用,但在大多数用例中,最好不要在 vba 中使用工作表函数。
    • 我的帖子只处理 OP 的当前问题。随时发布答案以建议替代代码以提高原始代码的性能:)
    【解决方案2】:

    @Siddharth Rout,不是批评:(

    使用字典的替代方法:

        Sub DictMatch()
            'set vars
            Dim arr, arr2, j As Long, dict As Object
            Set dict = CreateObject("Scripting.Dictionary") 'create dictionary lateB
            
            'source = lookupVars
            arr = Sheet1.Range("A1:A" & Sheet1.Cells(Rows.Count, 1).End(xlUp).Row).Value2 'load source
            For j = 1 To UBound(arr) 'traverse source
                dict(arr(j, 1)) = Empty
            Next j
            
            'compare
            arr2 = Sheet2.Range("A1").CurrentRegion.Value2 'load source
            For j = 1 To UBound(arr2)
                If dict.Exists(arr2(j, 1)) Then 'matching happens here, compare data from target with dictionary
                    arr(j, 1) = arr2(j, 2) 'write to target array if match
                End If
            Next j
            
            'dumb to sheet
            With Sheet1
                .Range(.Cells(1, 2), .Cells(UBound(arr), 2)) = arr 'dumping in col 2 but if you want to replace just change col nr
            End With
        End Sub
    

    【讨论】:

    • 哦,我没有感觉不好。我只是鼓励您发布答案;)
    • Sheet1 和 Sheet2 与问题中的 Sheets("Sheet3") 和 Sheets("Pod") 有什么关系?
    • 好吧,如果只是复制粘贴就不会有趣了,不是吗。
    • 如果arr2 = Sheets("Pod").Range("A1:B25") For j = 1 To UBound(arr2) 如果说UBound(arr) 是100,如何更新arr 中的所有元素?
    • 它没有。仅使用 col 1 和 2。 Col 1 用于查找,col2 用于替换 arr 中 org 值的值。只有当它们匹配时(我在工作表的 col 2 中添加匹配以进行测试,但在最终版本中它应该替换 col1 的值)。
    猜你喜欢
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2019-10-01
    • 2021-04-25
    • 1970-01-01
    • 2020-12-16
    • 2011-05-10
    • 2019-10-24
    相关资源
    最近更新 更多