Adding a comma within a text string based on a condtion

I have a column of text.  Within the column for some cells I have embedded numbers.  My goal is if I find a cell where a space is found between two numbers I want to add a comma.  An example is below.  My thought was to use the InStr function within VBA (I already have an existing loop that goes thru the column), but this function only seems like a solution if I wanted to add a comma once I found a space.  However, I ONLY want to add a comma if a space is found within the string AND if the space is found between 2 numbers.

Current
JinDandy
Favor18 500Bye
Chuckwagon100 000sick
JeffMandy

Desired
JinDandy
Favor18,500Bye
Chuckwagon100,000sick
JeffMandy
upobDaPlayaAsked:
Who is Participating?
 
Wayne Taylor (webtubbs)Connect With a Mentor Commented:
Regular Expressions are handy in situations like this. In the below "\d" signifies a single digit and "\s" signifies a space.

Sub ReplaceSpace()

    Dim cell As Range
    Dim rx As Object
    Set rx = CreateObject("VBScript.RegExp")
    rx.Pattern = "\d\s\d"
    
    For Each cell In Selection
        If rx.Test(cell.Value) Then
            cell.Value = rx.Replace(cell.Value, Replace(rx.Execute(cell.Value).Item(0).Value, " ", ","))
        End If
    Next
    
End Sub

Open in new window

2
 
Martin LissConnect With a Mentor Older than dirtCommented:
Try this macro. Change the Const's as needed.

Sub AddComma()
Dim strParts() As String
Dim lngLastRow As Long
Dim lngRow As Long
Dim intPart As Integer
Dim strNew As String
Const DATA_COL = "A"
Const DEST_COL = "B"
Const FIRST_ROW = 1


With ActiveSheet
    lngLastRow = .Range(DATA_COL & "1048576").End(xlUp).Row
    For lngRow = FIRST_ROW To lngLastRow
        strNew = ""
        strParts = Split(.Cells(lngRow, DATA_COL), " ")
        If UBound(strParts) > 0 Then
            For intPart = 0 To UBound(strParts) - 1
                If IsNumeric(Right$(strParts(intPart), 1)) And IsNumeric(Left$(strParts(intPart + 1), 1)) Then
                    strNew = strNew & strParts(intPart) & "," & strParts(intPart + 1)
                    intPart = intPart + 1
                Else
                    strNew = strNew & strParts(intPart) & " " & strParts(intPart + 1)
                End If
            Next
        Else
            strNew = .Cells(lngRow, DATA_COL)
            .Cells(lngRow, DEST_COL) = strNew
        End If
    Next
End With
End Sub

Open in new window

1
 
upobDaPlayaAuthor Commented:
Both approaches make sense - I used the reg solution
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.