Soulfire
Soulfire

Reputation: 4296

Placing brackets around numbers in a string

I need to add brackets around the numbers in a string found in cells on my Excel worksheet.

For example, say I am given:

913/(300+525)

I need to get this in return:

[913]/([300]+[525])

The equations are fairly simple, should only have to deal with + - * / ( ) characters.

I attempted looping through the string character by character using the MID function but I can't get the loop(s) working correctly and end up getting a jumbled mess of random brackets and numbers back. I also considered using regular expressions but I've never used them before and have no idea if this would be a good application.

Please let me know if you need anything else. Thank you for your time!

They can be decently long. Here is another example:

I have:

(544+(1667+1668+1669+1670+1671+1672+1673)-1674)

But I need:

([544]+([1667]+[1668]+[1669]+[1670]+[1671]+[1672]+[1673])-[1674])

Upvotes: 2

Views: 392

Answers (2)

Siddharth Rout
Siddharth Rout

Reputation: 149295

Here is a way which caters for Decimal numbers.

'~~> Add here whatever operators your equation
'~~> is likely to have
Const delim As String = "+()-/"

Sub Sample()
    Dim MyAr
    Dim sSamp As String

    sSamp = "(5.44+(16.67+1668+1669+1670+1671+1672+1673)-1674)"

    MyAr = Split(GetNewString(sSamp))

    For i = 0 To UBound(MyAr)
        sSamp = Replace(sSamp, MyAr(i), "[" & MyAr(i) & "]")
    Next i

    Debug.Print sSamp
End Sub

Function GetNewString(s As String) As String
    Dim sTemp As String

    sTemp = s

    For i = 1 To Len(delim)
        sTemp = Replace(sTemp, Mid(delim, i, 1), " ")
    Next i

    Do While InStr(1, sTemp, "  ")
        sTemp = Replace(sTemp, "  ", " ")
    Loop

    GetNewString = Trim(sTemp)
End Function

Input

"(5.44+(16.67+1668+1669+1670+1671+1672+1673)-1674)"

Output

([5.44]+([16.67]+[1668]+[1669]+[1670]+[1671]+[1672]+[1673])-[1674])

Upvotes: 2

user1274820
user1274820

Reputation: 8144

I just threw this together but it should work

Function generateBrackets(Equation As String) As String

Dim temp As String
Dim brackets As Boolean
Dim x 'If we're using Option Explicit, or just to be safe

For x = 1 To Len(Equation)
    If Not IsNumeric(Mid(Equation, x, 1)) And brackets = False Then
        temp = temp & Mid(Equation, x, 1)
    ElseIf Not IsNumeric(Mid(Equation, x, 1)) And brackets = True Then
        temp = temp & "]" & Mid(Equation, x, 1)
        brackets = False
    ElseIf IsNumeric(Mid(Equation, x, 1)) And brackets = False Then
        temp = temp & "[" & Mid(Equation, x, 1)
        brackets = True
    ElseIf IsNumeric(Mid(Equation, x, 1)) And brackets = True Then
        temp = temp & Mid(Equation, x, 1)
    End If
Next x

generateBrackets = temp

End Function

enter image description here

Upvotes: 3

Related Questions