I've been experimenting with different ways to efficiently remove multiple commas from a text string. So far the best performers are these three:
'Use VBA replace function, looping until all multiple commas are replaced
Function CollapseCommas2(ByVal AnyString As String) As String
Dim DDelim As String
Dim S1 As String
Dim Delimiter As String
Delimiter = "," 'in this case, commas
DDelim = Delimiter & Delimiter 'double delimiters
S1 = AnyString
If InStr(AnyString, DDelim) > 0 Then
Do
S1 = VBA.Replace(S1, DDelim, Delimiter, 1, -1)
Loop Until InStr(S1, DDelim) = 0
End If
CollapseCommas2 = S1
End Function
'Use excel Application.WorksheetFunction.Substitute, looping until all multiple commas are replaced
Function CollapseCommas2b(ByVal AnyString As String) As String
Dim DDelim As String
Dim S1 As String
Dim Delimiter As String
Delimiter = "," 'in this case, commas
DDelim = Delimiter & Delimiter 'double delimiters
S1 = AnyString
If InStr(AnyString, DDelim) > 0 Then
Do
S1 = Application.WorksheetFunction.Substitute(S1, DDelim, Delimiter)
Loop Until InStr(S1, DDelim) = 0
End If
CollapseCommas2b = S1
End Function
'Slight variation on Fn3, using Application.WorksheetFunction.Trim instead of Application.Trim
Function CollapseCommas3a(ByVal AnyString As String) As String
Dim DDelim As String
Dim S1 As String
Dim Delimiter As String
Delimiter = "," 'in this case, commas
DDelim = Delimiter & Delimiter 'double delimiters
S1 = AnyString
S1 = VBA.Replace(S1, " ", Chr(248), 1, -1) 'replace spaces with obscure character unlikely to be found in the string
S1 = VBA.Replace(S1, Delimiter, " ", 1, -1) 'replace commas with spaces
S1 = Application.WorksheetFunction.Trim(S1) 'this is fast and unlike vba.Trim, collapses internal spaces
S1 = VBA.Replace(S1, " ", Delimiter, 1, -1) 'restore the commas
S1 = VBA.Replace(S1, Chr(248), " ", 1, -1) 'restore the spaces
CollapseCommas3a = S1
End Function
Is there another approach I'm overlooking? Other experiments attached.
Thanks.