[英]How To Vlookup To Return Multiple Values In One Cell In Excel?
So I have the code that pastes multiple values into one cell but I was hoping to be able to put a semicolon in between the cell's value.所以我有将多个值粘贴到一个单元格的代码,但我希望能够在单元格的值之间放置一个分号。
This code allows a vlookup to find multiple cell values and output them in one cell.此代码允许 vlookup 查找多个单元格值并将它们输出到一个单元格中。
Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)
'Update 20150310
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
When I do this it does put a semicolon in between the values like I want, but also has a billion semicolons after.当我这样做时,它确实在我想要的值之间放了一个分号,但后面还有十亿个分号。
I'd work with an array for this.我会为此使用一个数组。 Start by sizing it to fit the entire source:
首先调整它的大小以适合整个源:
Dim results As Variant
ReDim results(1 To pWorkRng.Count)
Then maintain a counter for the index of the last item in that array, and write at that index:然后为该数组中最后一项的索引维护一个计数器,并在该索引处写入:
Dim currentIndex As Long
For Each rng In pWorkRng
If Not IsError(rng.Value) Then
If rng.Value = pValue Then
currentIndex = currentIndex + 1
results(currentIndex) = rng.Offset(0, pIndex - 1)
End If
End If
Next
When the loop completes, you'll have all the results up to currentIndex
, and then a bunch of Empty
values;循环完成后,您将获得最多
currentIndex
所有结果,然后是一堆Empty
值; truncate the array with ReDim Preserve
:使用
ReDim Preserve
截断数组:
ReDim Preserve results(1 To currentIndex)
And now you can return a string with all the results, using String.Join
:现在您可以使用
String.Join
返回一个包含所有结果的字符串:
MYVLOOKUP = String.Join(results, ";")
If Mathieu Guindons method doesn't work then, try to add the following to your code after the following line:如果 Mathieu Guindons 方法不起作用,请尝试在以下行之后将以下内容添加到您的代码中:
xResult = xResult & ";" & rng.Offset(0, pIndex - 1)
Do While (InStr(xResult, ";;") > 0)
xResult = Replace(xResult, ";;", ";")
Loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.