Vlookup返回多个值

我正在尝试做Vlookup来返回多个值。 但是,该function需要很长时间才能加载。 有什么办法可以让它更快? 我从网上获得了这个function: 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 

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

将范围向下切换到数据的活动区域,或者使用“相交”将整列引用修剪到.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通常区分大小写。