以下是将上述代码修改为在第二个工作表查找范围的示例: Sub VLookupFunction() Dim lookupValue As Variant Dim lookupRange As Range Dim resultRange As Range Dim result As Variant Dim i As Long Dim ws As Worksheet

' 设置要查找的值
lookupValue = 'apple'
' 选择要查找的工作表
Set ws = ThisWorkbook.Worksheets(2)
' 设置要查找的范围
Set lookupRange = ws.Range('A2:A' & ws.Cells(Rows.Count, 'A').End(xlUp).Row)
' 设置要返回结果的范围
Set resultRange = ws.Range('B2:B' & ws.Cells(Rows.Count, 'B').End(xlUp).Row)
' 遍历每一行数据,并在每一行中执行VLOOKUP函数
For i = 1 To lookupRange.Rows.Count
    ' 使用VBA的Match函数查找匹配的行数
    Dim matchRow As Long
    matchRow = Application.Match(lookupValue, lookupRange.Cells(i), 0)
    ' 使用VBA的Index函数返回对应的结果
    If Not IsError(matchRow) Then
        result = Application.Index(resultRange.Cells(i), matchRow, 1)
    Else
        result = 'N/A'
    End If
    ' 将结果输出到单元格中
    ws.Range('C' & i + 1).Value = result
Next i

End Sub 在这个示例中,我们选择要查找的工作表,并设置要查找的范围和返回结果的范围。然后遍历每一行数据,并在每一行中执行VLOOKUP函数。最后将结果输出到相应的单元格中。如果查找不到匹配的值,我们将返回'N/A'。如果需要,你可以把以上代码进行修改来适应自己的数据查找需求。


原文地址: https://www.cveoy.top/t/topic/jBd2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录