2

currently with the codes below, output would be ~ abc~ etc~ etc~. How do I remove the first ~. So it should start with abc straight away, not ~.

Function SpecialLookup(lookup_value As String, src_rng As Range, column_index As Long)

    Dim rng As Range
    Dim xResult As String
    xResult = ""
    For Each rng In src_rng
        If rng = lookup_value Then
            xResult = xResult & "~ " & rng.Offset(0, column_index - 1).Value
        End If
    Next
    SpecialLookup = xResult
End Function
Josh Ng
  • 198
  • 14

3 Answers3

4

Mid should do the trick


SpecialLookup = Mid(xResult, 3, Len(xResult))
urdearboy
  • 14,439
  • 5
  • 28
  • 58
  • 6
    in vba the third criterion is optional you can get the same with `SpecialLookup = Mid(xResult, 2)` and I believe it should `SpecialLookup = Mid(xResult, 3)` as the prefix is `'~ '` – Scott Craner Apr 23 '20 at 15:13
  • @ScottCraner good catch on the leading space. I did not know VBA defaults to full length of string. Thanks for sharing! – urdearboy Apr 23 '20 at 15:13
  • Hey urdeaboy and scott craner! Thanks so much to both! works perfectly. – Josh Ng Apr 23 '20 at 15:15
3

I like this pattern:

Function SpecialLookup(lookup_value As String, src_rng As Range, column_index As Long)
    Dim rng As Range
    Dim xResult As String, sep as String
    For Each rng In src_rng
        If rng = lookup_value Then
            xResult = xResult & sep & rng.Offset(0, column_index - 1).Value
            sep = "~ " '<<<<<
        End If
    Next
    SpecialLookup = xResult
End Function
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
2

another option is an IF:

Function SpecialLookup(lookup_value As String, src_rng As Range, column_index As Long)

    Dim rng As Range
    Dim xResult As String
    xResult = ""
    For Each rng In src_rng
        If rng = lookup_value Then
            If xResult = "" Then
                xResult = rng.Offset(0, column_index - 1).Value
            Else
                xResult = xResult & "~ " & rng.Offset(0, column_index - 1).Value
            End If
        End If
    Next
    SpecialLookup = xResult
End Function
Scott Craner
  • 148,073
  • 10
  • 49
  • 81