Search code examples
excelvbastringreplacewhitespace

VBA - Replace only a single whitespace (" ") in a string with a character


I have a string with the following text:

16/2730 99 16/2730 97 16/2730 81 16/2730 76 16/2730 103 16/2730 102 16/2730 101

I would like to replace the single whitespaces (" ") with another character "-". My desired result would be:

16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101

Any suggestions on how to replace the single whitespaces with another character, while leaving the multiple whitespaces alone?


Solution

  • A further approach in addition to Tim Williams' valid tips in comments might be the following one (assuming search sequences of digits, slashes and single blanks " " which can be identified as numeric):

    • Split the string by blanks into a variant array,
    • add a hyphen to elements with a numeric right neighbour only,
    • fill ""-elements with a blank again and
    • join the array setting the delimiter to "".

    Example

    Sub Example()
        Dim s As String
        s = "16/2730 99    16/2730 97    16/2730 81    16/2730 76    16/2730 103    16/2730 102    16/2730 101"
    
        Dim tmp As Variant
        tmp = Split(s)
        'Debug.Print Join(tmp, "|")                  ' optional display in immediate window
        'Loop through splitted array elements
        Dim i As Long
        For i = 0 To UBound(tmp) - 1
            If IsNumeric(tmp(i + 1)) Then            ' if immediate right neighbour is numeric
                tmp(i) = tmp(i) & "-"                ' .. add a hyphen to the current element
            ElseIf tmp(i) = "" Then                  ' if current element was a blank
                ' .. give back the former blank values (<~~ Edited ~~>)
                tmp(i) = IIf(IsNumeric(Right(tmp(i + 1), 1)), "  ", " ")
            End If
        Next i
        Debug.Print Join(tmp, "")                    ' put completed elements together again
    
    End Sub
    

    Results in VB Editor's immediate window

    16/2730-99 16/2730-97 16/2730-81 16/2730-76 16/2730-103 16/2730-102 16/2730-101