Search code examples
excelvbastringcut

How to cut a part of a string?


I'm trying to cut duplicates from a string i have.

The string looks like this:

word-1\word-2\word-3\word-3\word-3\word-3

And I wish it look like this: (without the duplications).

word-1\word-2\word-3

So far I thought of put the string into an array and split to items by \ . I don't really know how I suppose to cut the duplications. Moreover, I don't know how many duplicates gonna be.

This is what I got so far:

Sub Split_and_remove()
  ' split items on \
  Dim item As String, newItem As String
  Dim items As Variant, newItems As Variant
  item = Sheet1.Range("A1").Value2
  items = Split(item, "\")
  newItems = items(0) + "\" + items(1) + "\" + items(2)
  Sheet1.Range("A4").Value2 = newItems
End Sub

Thanks!


Solution

  • This is an implementation with a collection, so you don't need an external object like a dictionary:

    Public Function GetUniqueValues(ByVal valueString As String, ByVal delimiter As String) As String
        With New Collection
            On Error Resume Next
    
            Dim item As Variant
            For Each item In Split(valueString, delimiter)
                .Add item, item
    
                If Err.Number = 0 Then _
                    GetUniqueValues = GetUniqueValues & item & delimiter
    
                Err.Clear
            Next item
        End With
    
        GetUniqueValues = Left(GetUniqueValues, Len(GetUniqueValues) - Len(delimiter))
    End Function
    

    It can be used with all variants of VBA, not only Excel.