我有VLookup的代码。问题是我想对国家名称使用多个变体,因此在给出错误之前应该全部使用它们。因此,应先查看A列,然后查看B列,然后查看C列。
我的数据(“国家/地区”表):
我的代码:
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
答案 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