Forum Discussion
M.Emre CANAL
Apr 24, 2017Copper Contributor
To inverse the words
I want write inversely the words in the same cell. For example; ( Washington-Paris-Ankara-Madrid) inversely>>(Madrid-Ankara-Paris-Washington) Thank you
SergeiBaklan
Apr 26, 2017Diamond Contributor
Okay, one more way to reverse the sequence of words in the string is to use VBA, especially taking into account the reverse is to be done in the same cell.
Lot of samples exists. Code below works if stay on the cell and run that macro
Sub ReverseWords()
Dim InputStr As String
Dim ResultStr As String
Dim InputArray() As String
Dim OutputStr As String
Dim SeparatorStr As String
Dim WordsCount As Integer
Dim WorkRng As Range
SeparatorStr = "-"
'Take string from selected cell
Set WorkRng = Application.Selection
InputStr = WorkRng.Value
'Split and put into an array
InputArray = Split(InputStr, SeparatorStr)
WordsCount = UBound(InputArray)
'Combine all the words in reverse
ResultStr = ""
xSep = ""
For i = WordsCount To 0 Step -1
If i = 0 Then
xSep = ""
Else: xSep = "-"
End If
ResultStr = ResultStr & InputArray(i) & xSep
Next
WorkRng.Value = ResultStr
End SubI believe it could be expanded on the case when range of cells is selected to reverse words in each of it.