因此,我有将多个值粘贴到一个单元格中的代码,但我希望能够在单元格的值之间放入分号。
此代码允许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
当我这样做时,它确实将分号放在了我想要的值之间,但之后还有十亿个分号。
答案 0 :(得分:1)
我将为此使用数组。首先调整其大小以适合整个源:
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, ";")
答案 1 :(得分:0)
如果Mathieu Guindons方法不起作用,请尝试在以下行之后将以下内容添加到您的代码中:
xResult = xResult & ";" & rng.Offset(0, pIndex - 1)
Do While (InStr(xResult, ";;") > 0)
xResult = Replace(xResult, ";;", ";")
Loop