Search code examples
excelvba

Vlookup Range Without Getting #NA Value if is Not Found


I have this code that works perfectly fine, but how do I make it to avoid getting #NA Value.

Every time I run the code, VBA will delete the existing value and change it to #NA while it doesn't have to be changed if there is no match.

this is my current code

Dim sws As Worksheet: Set sws = wb.Sheets("Existing")
    Dim srg As Range: Set srg = sws.Columns("A:AJ")
    
    Dim dws As Worksheet: Set dws = wb.Sheets("Existing")
    Dim dlRow As Long
    dlRow = dws.Cells(dws.Rows.Count, "A").End(xlUp).Row
    
    Dim i As Long
    
    For i = 2 To lastRowSourceSheet
        dws.Cells(i, "P").Value = Application.VLookup(dws.Cells(i, "A").Value, srg, 35, 0)
    Next i
    
    For i = 2 To lastRowSourceSheet
        dws.Cells(i, "Q").Value = Application.VLookup(dws.Cells(i, "A").Value, srg, 36, 0)
    Next i

I hope it makes sense.


Solution

  • EDIT: updated with tested code.

    You only need to check for a match once:

    Sub BlahBlah()
        '.....
        Dim wb As Workbook, sws As Worksheet, dws As Worksheet, i As Long, m As Variant
    
        Set wb = ThisWorkbook
        Set sws = wb.Sheets("Source")  'really the same worksheet?
        Set dws = wb.Sheets("Source")
        
        For i = 2 To dws.Cells(dws.Rows.Count, "A").End(xlUp).Row
            m = Application.Match(dws.Cells(i, "A").Value, sws.Columns("A"), 0)
            If Not IsError(m) Then  'got a match in ColA?
                AddIfNotNA dws.Cells(i, "P"), sws.Cells(m, 35).Value
                AddIfNotNA dws.Cells(i, "Q"), sws.Cells(m, 36).Value
            End If
        Next i
        '...
        '...
    End Sub
    
    'Add value `v` to cell `c` if `v` is not NA#
    Sub AddIfNotNA(c As Range, v)
        If Not IsError(v) Then
            c.Value = v 'not any type of error: add value
        Else
            If v <> CVErr(xlErrNA) Then c.Value = v 'not #NA  -add value
        End If
    End Sub