[英]Problem with UDF designed to concatenate multiple matches in vlookup
對於我的生活,我無法弄清楚為什么這不起作用。 它給了我一個 #VALUE 錯誤。
我正在使用 ActiveSheet,因為我會將它放在許多不同的工作表上,而且我不想為此在函數中添加一個字段。
LookupRange 旨在查找 ActiveSheet 上包含數據的最后一行。
我的查找值從 B5 開始並無限期擴展,所需的匹配項位於 O 列(第 15 列)中。
Function EmailConcat(LookupValue As String)
Application.Volatile
Dim i As Long
Dim Result As String
Dim LookupSheet As Worksheet
Dim LookupRange As Range
Set LookupSheet = Application.ActiveSheet
LookupRange = LookupSheet.Cells.Find(What:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row
For i = 5 To LookupRange.Rows.Count
If LookupSheet.Cells(i, 2) = LookupValue Then
Result = Result & LookupSheet.Cells(i, 15) & "; "
End If
Next i
EmailConcat = Left(Result, Len(Result) - 2)
End Function
使用ThisCell
確保結果准確,並將查找列讀入數組以獲得更好的性能:
Function EmailConcat(LookupValue As String)
Application.Volatile
Dim vals, rv, i As Long, sep As String
If LookupValue <> "" Then
With Application.ThisCell.Worksheet
vals = .Range(.Range("B5"), .Cells(.Rows.Count, 2).End(xlUp))
For i = 1 To UBound(vals, 1)
If vals(i, 1) = LookupValue Then
rv = rv & sep & .Cells(4 + i, 15).Value
sep = "; "
End If
Next i
End With
End If
EmailConcat = rv
End Function
當使用 Range 或 Cells 等不帶限定符時,它們指的是ActiveWorkbook
的ActiveSheet
。
Function EmailConcat(LookupValue As String)
Application.Volatile
Const cFirst As String = "B5"
Const cCol As Variant = "O"
Dim i As Long
Dim Result As String
Dim LastRow As Long
LastRow = Cells.Find("*", , xlFormulas, xlWhole, xlByRows, xlPrevious).Row
For i = Range(cFirst).Row To LastRow
If Cells(i, Range(cFirst).Column) = LookupValue Then
Result = Result & Cells(i, cCol) & "; "
End If
Next i
EmailConcat = Left(Result, Len(Result) - 2)
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.