【问题标题】:Vlookup return multiple valuesVlookup 返回多个值
【发布时间】:2017-05-19 01:24:50
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 当你得到'网上的功能'时,认可原作者是一种礼貌。

标签: excel vba excel-formula vlookup textjoin


【解决方案1】:

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

要么将范围缩减到数据的活动区域,要么使用 Intersect 将完整列引用缩减到 .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 通常区分大小写。

【讨论】:

  • 您也可以使用textjoin 执行此操作。见Concatenate multiple results from an index match
  • 如何在结果后添加逗号。我将它添加到这一行:xResult = xResult & " , " & rng.Offset(0, pIndex - 1)。但是它显示为 " , a , b , c"
  • 听起来像是想以逗号结尾。如果是这种情况,则使用 xResult = xResult & rng.Offset(0, pIndex - 1) & ", " 反转字符串连接顺序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多