Vlookup return 多个值

Vlookup return multiple values

我正在尝试对 return 多个值进行 Vlookup。但是,该功能需要很长时间才能加载。有什么办法让它更快吗?我从网上得到了这个功能:https://www.extendoffice.com/documents/excel/2706-excel-vlookup-return-multiple-values-in-one-cell.html

  Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)
  Dim rng As Range
  Dim xResult As String
  xResult = ""
  For Each rng In pWorkRng
   If rng = pValue Then
    xResult = xResult & " " & rng.Offset(0, pIndex - 1)
  End If
 Next
 MYVLOOKUP = xResult
 End Function

这是子

中的代码
 Sub sort()
Dim x As Integer
Dim result As Variant
Dim name As String
 Application.ScreenUpdating = False
  x = 10
 Do Until IsEmpty(Sheet9.Cells(x, 1).Value)
 name = Sheet9.Cells(x, 1).Value
 result = MYVLOOKUP(name, Sheet9.Range("K:M"), 3)
 Sheet9.Cells(x, 4).Value = result
 x = x + 1
 Loop
 End Sub

当您使用 Sheet9.Range("K:M") 作为 pWorkRng 参数传入 UDF 时,它会在 For Each rng In pWorkRng 循环中使用。这意味着您将要检查整整三列或 3,145,728 个单元格;其中大部分是完全空的,其中两列在任何情况下都不是 VLOOKUP 所必需的。难怪为什么事情 运行 很慢。

要么将范围缩小到数据的活动区域,要么使用 Intersect to trim 全列引用到 .UsedRange。

Option Explicit

Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)
    Dim rng As Range
    Dim xResult As String

    xResult = vbnullstring
    'the next line trims pWorkRng down to the .UsedRange
    Set pWorkRng = Intersect(pWorkRng, pWorkRng.Parent.UsedRange)

    'if you only want to examione the first column then use the following
    'For Each rng In pWorkRng.columns(1)
    'if you want to look through K, L and M for pValues then use this one,
    For Each rng In pWorkRng
        If rng = pValue Then
            xResult = xResult & " " & rng.Offset(0, pIndex - 1)
       End If
    Next
    MYVLOOKUP = trim(xResult)
 End Function

我添加了一个仅查看第一列的选项。您的比较也区分大小写;你可能真的想要那个,但 VLOOKUP 通常 区分大小写。