1

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.

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.

8
  • Can you put Debug.Print rng.Offset(0, pIndex - 1) before xResult = xResult & ";" & rng.Offset(0, pIndex - 1) and see what that's returning? Commented Jan 22, 2019 at 20:56
  • 1
    If you have Office 365: =TEXTJOIN(";",TRUE,IF(A1:A1000="MyValue",D1:D1000,"")) As an Array Formula with Ctrl-Shift-Enter Commented Jan 22, 2019 at 21:00
  • @dwirony it still has a bunch of ; after Commented Jan 22, 2019 at 21:01
  • @scott craner where am I adding that? Commented Jan 22, 2019 at 21:02
  • it is a formula that you add on the sheet changing the ranges to the desired input and output, it is not vba Commented Jan 22, 2019 at 21:03

2 Answers 2

1

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; truncate the array with ReDim Preserve:

ReDim Preserve results(1 To currentIndex)

And now you can return a string with all the results, using String.Join:

MYVLOOKUP = String.Join(results, ";")
Sign up to request clarification or add additional context in comments.

Comments

0

If Mathieu Guindons method doesn't work then, try to add the following to your code after the following line:

xResult = xResult & ";" & rng.Offset(0, pIndex - 1)

    Do While (InStr(xResult, ";;") > 0)
        xResult = Replace(xResult, ";;", ";")
    Loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.