2017-05-19 287 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