VB and VBA Users Source Code: Removing duplicate values from a delimited string
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
VB/VBA Source Code
Removing duplicate values from a delimited string
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Friday, April 22, 2005
Hits:
2323
Category:
Visual Basic General
Article:
Below is a function and demonstration source code that shows how to remove duplicate values from a delimited string. 'Purpose : Removes duplicate values from a delimited string. 'Inputs : sDelimString The delimited string to remove the duplicate values from. ' sDelimiter The string delimiter. ' [eCompare] The method of comparison. 'Outputs : Returns the input string "sDelimString" with any duplicate values removed. 'Author : Andrew Baker 'Date : 13/Jul/2001 'Notes : Function RemoveDuplicates(sDelimString As String, sDelimiter As String, Optional eCompare As VbCompareMethod = vbTextCompare) As String Dim asValues() As String Dim lThisValue As Long Dim sExistingValues As String Dim bEndDelim As Boolean If Len(sDelimString) Then 'Check if there is an end delimiter bEndDelim = Right$(sDelimString, Len(sDelimiter)) = sDelimiter 'Split the string into an array asValues = Split(sDelimString, sDelimiter) 'Loop over the items in the string For lThisValue = 0 To UBound(asValues) 'Check if the item is already in the string If InStr(1, RemoveDuplicates, asValues(lThisValue) & sDelimiter, eCompare) = 0 Then 'The value is unique, add it to the results RemoveDuplicates = RemoveDuplicates & asValues(lThisValue) & sDelimiter End If Next If bEndDelim = False Then 'Remove final delimiter RemoveDuplicates = Left(RemoveDuplicates, Len(RemoveDuplicates) - Len(sDelimiter)) End If End If End Function 'Demonstration routine Sub Test() Dim sTest As String sTest = "andrew,baker,is,ace,andrew,IS," sTest = RemoveDuplicates(sTest, ",", vbTextCompare) Debug.Print sTest End Sub
Terms and Conditions
Support this site
Download a trial version of the Excel Workbook Rebuilder