用于反转所选文本的Word宏

问题描述 投票:0回答:1

我想编写一个脚本来重新排列选定的行,其中第一行成为最后一行。

示例输入:

世界你好。
我的名字是汤姆。
我可能比你大。
也许不是。

示例输出:

也许不是。
我可能比你大。
我的名字是汤姆。
世界你好。

这是 ChatGPT 为我创建的,但不幸的是它不太有效:

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

我尝试在 Google 和 ChatGPT 中搜索。

vba ms-word macros
1个回答
0
投票

更容易查找段落而不是操纵整个文本。

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

© www.soinside.com 2019 - 2024. All rights reserved.