我正在尝试执行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
答案 0 :(得分:2)
当您使用传递给UDF的Sheet9.Range("K:M")
作为 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通常不区分大小写。