2017-05-19 247 views
0

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

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 
+0

当您获得'*来自在线*的功能'时,对原始作者进行认证被认为是很好的礼仪。 – Jeeped

回答

2

当您使用Sheet9.Range("K:M")传递到UDF作为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通常不区分大小写而不是

+0

你也可以用[tag:textjoin]来做到这一点。请参阅[从索引匹配连接多个结果](http://stackoverflow.com/questions/43352819/concatenate-multiple-results-from-an-index-match)。 – Jeeped

+0

如何在结果后添加逗号。我将它添加到这行:xResult = xResult&“,”&rng.Offset(0,pIndex - 1)。但它显示为“,a,b,c” –

+0

这听起来像是想以逗号结尾。如果是这种情况,请使用'xResult = xResult&rng.Offset(0,pIndex - 1)&“,”' – Jeeped