Word macro for reversing selected text

24 Views Asked by At

I would like to write a script that rearranges selected lines wherein the first line becomes the last line.

Sample Input:

Hello World.
My Name is Tom.
I'm maybe older than you.
maybe not.

Sample Output:

maybe not.
I'm maybe older than you.
My Name is Tom.
Hello World.

This is what ChatGPT created for me, but unfortunately it doesn't quite work:

Sub ReverseLines()
    Dim SelectionRange As Range
    Dim Text As String
    Dim ReversedText As String
    Dim i As Integer
    
    'Check if text is selected
    If Selection.Type = wdSelectionIP Then
        MsgBox "Please select the text you want to reverse.", vbExclamation
        Exit Sub
    End If
    
    'Save the selected text
    Set SelectionRange = Selection.Range
    Text = SelectionRange.Text
    
    'Reverse the selected text
    ReversedText = ""
    For i = Len(Text) To 1 Step -1
        ReversedText = ReversedText & Mid(Text, i, 1)
    Next i
    
    'Replace selection with reversed text
    SelectionRange.Text = ReversedText
End Sub

I tried searching in Google and ChatGPT.

1

There are 1 best solutions below

0
Black cat On

It is easier to look for paragraphs and not manipulate the whole text.

Sub ReverseLines()
'Dim SelectionRange As Range
'Dim Text As String
Dim ReversedText As String
Dim i As Integer

'Check if text is selected
If Selection.Type = wdSelectionIP Then
    MsgBox "Please select the text you want to reverse.", vbExclamation
    
    Exit Sub
End If

'Save the selected text
'Set SelectionRange = Selection.Range
'Text = SelectionRange.Text

'Reverse the selected text
ReversedText = ""
For i = Selection.Paragraphs.Count To 1 Step -1
    ReversedText = ReversedText & Selection.Paragraphs(i).Range.Text
Next i