0

我正在尝试执行 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
4

1 回答 1

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 通常区分大小写。

于 2017-05-19T01:55:34.880 回答