[英]How To Vlookup To Return Multiple Values In One Cell In Excel?
所以我有將多個值粘貼到一個單元格的代碼,但我希望能夠在單元格的值之間放置一個分號。
此代碼允許 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
當我這樣做時,它確實在我想要的值之間放了一個分號,但后面還有十億個分號。
我會為此使用一個數組。 首先調整它的大小以適合整個源:
Dim results As Variant
ReDim results(1 To pWorkRng.Count)
然后為該數組中最后一項的索引維護一個計數器,並在該索引處寫入:
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
循環完成后,您將獲得最多currentIndex
所有結果,然后是一堆Empty
值; 使用ReDim Preserve
截斷數組:
ReDim Preserve results(1 To currentIndex)
現在您可以使用String.Join
返回一個包含所有結果的字符串:
MYVLOOKUP = String.Join(results, ";")
如果 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.