查找具有不同变体的形式

时间:2019-10-16 16:34:58

标签: excel vba

我有VLookup的代码。问题是我想对国家名称使用多个变体,因此在给出错误之前应该全部使用它们。因此,应先查看A列,然后查看B列,然后查看C列。

我的数据(“国家/地区”表):

enter image description here

我的代码:

Sub PasteFormulaToRange()

    Dim refRng As Range, ref As Range, dataRng As Range

    Set refRng = ThisWorkbook.Worksheets("Main").Range("K2:K969") 'horizontal range of look up values
    Set dataRng = ThisWorkbook.Worksheets("Countries").Range("A2:D198") 'data block you want to look up value in

    For Each ref In refRng
        ref.Offset(0, 2) = Application.WorksheetFunction.VLookup(ref, dataRng, 4, False)
    Next ref
End Sub

1 个答案:

答案 0 :(得分:3)

VLookup无法搜索多列,您要做的是使用Range.Find查找行,然后提取列4中的数据。Range.Find可以使用更多参数在这里引用https://excelmacromastery.com/excel-vba-find/

Sub NewPasteFormulatoRange()

    Dim refRng As Range, ref As Range, dataRng As Range
    Dim foundrow as Long
    Set refRng = ThisWorkbook.Worksheets("Main").Range("K2:K969") 'horizontal range of look up values
    Set dataRng = ThisWorkbook.Worksheets("Countries").Range("A2:C198") 'data block you want to look up value in

    For Each ref In refRng
        Set findref = dataRng.Find(ref)
        If Not findref Is Nothing Then
            foundrow = findref.Row
            ref.Offset(0, 2) = ThisWorkbook.Worksheets("Countries").Cells(foundrow, 4)
        End If
    Next ref
End Sub