繁体   English   中英

如何输入相同的值来代替 Vlookup `#N/A`

[英]How can I input same value in place of Vlookup `#N/A`

我想从其简短形式更新端口代码。 假设我有端口代码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

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

FinalResult = Application.VLookup(LookupValue, Table_Range, 2, False)

If IsError(FinalResult) Then FinalResult = LookupValue

rng.Value = FinalResult

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

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

@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

暂无
暂无

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

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