• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Find Last Occurence Of Space In String?

Luke, am I close?


Sub Add_Brace2LastWord()

Dim Cell As Range

Dim MyString As String

Dim FindLastBrace As String


For Each Cell In Range("A1", Range("A65536").End(xlUp))

MyString = Cell.Value


FindLastBrace = Mid(Cell, Len(Cell) - 1, 1)


If FindLastBrace Like "}" Then

MyString = WorksheetFunction.Substitute(MyString, " ", " {", Len(MyString) - Len(WorksheetFunction.Substitute(MyString, " ", "")))


Cell.Value = MyString

End If

Next Cell

End Sub
 
Pretty close. You can save a few steps by not checking for a space by using a "resume next on error" for the substitution.


Code:
Sub Add_Brace2LastWord()

Dim Cell As Range

Dim MyString As String


For Each Cell In Range("A1", Range("A65536").End(xlUp))

MyString = Cell.Value

On Error Resume Next

MyString = WorksheetFunction.Substitute(MyString, " ", "}", Len(MyString) _

- Len(WorksheetFunction.Substitute(MyString, " ", "")))

On Error GoTo 0

Cell.Value = MyString

Next

End Sub
 
Absolutely fab.


But it throws the brace "{" on all last spaces in every string.

The "{" is backwards in the code above but that's ok ; )


However, do I tweak it so it only places it on strings that end with "}"


I was trying to use this below but it doesn't work.


FindLastBrace = Mid(Cell, Len(Cell) - 1, 1)


If FindLastBrace Like "}" Then

''run the code you just helped me with
 
Back
Top