【问题标题】:Moving words within a text在文本中移动单词
【发布时间】:2017-04-18 20:39:01
【问题描述】:

我正在尝试创建两个键盘快捷键,让我可以在文本中快速左右移动选定的单词。所选文本应向左或向右移动一个单词。 这是我想做的事

1) 选择单词,例如“这是”在句子“这是一棵树”中 2) 按例如ctrl + alt + 向右箭头 3) 句子现在读作“a this is tree” 4) 再次按 ctrl alt + 向右箭头 5) 这句话现在读作“这是一棵树”

我们的想法是替换剪切/粘贴步骤,让流程更高效、更顺畅。 我对VB一窍不通,但是通过Word的宏函数设法接近了。

Sub moveRight()
'moveRight Macro
Selection.Cut
Selection.moveRight Unit:=wdWord, Count:=1
Selection.PasteAndFormat (wdFormatOriginalFormatting)
End Sub

这个功能的问题是选中的词一旦粘贴就不再被选中。因此,再次触发该功能(=将文本移动多个单词)会导致错误(我必须再次选择相关文本)。有什么方法可以让选中的词在粘贴后保持选中状态,这样我就可以重复触发这个功能了?

非常感谢。

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    您可能想试试这个解决方案。下面的前两个过程应该由您的键盘快捷键调用。两者都调用相同的执行子,但参数不同。

    Sub MoveSelectionLeft()
        ' call with keyboard shortcut
        GetSelection True
    End Sub
    
    Sub MoveSelectionRight()
        ' call with keyboard shortcut
        GetSelection False
    End Sub
    
    Private Sub GetSelection(ByVal ToLeft As Boolean)
        ' 22 Apr 2017
    
        Dim Rng As Range
        Dim SelTxt As String                    ' selected text (trimmed)
        Dim Sp() As String
    
        Set Rng = Selection.Range
        With Rng
            SelTxt = Trim(.Text)
            If ToLeft Then
                .MoveStart wdWord, -1
            Else
                .MoveEnd wdWord, 1
            End If
            Sp = Split(Trim(.Text))
    
            If ToLeft Then
                .Text = SelTxt & " " & Sp(0) & " "
            Else
                .Text = Sp(UBound(Sp)) & " " & SelTxt & " "
            End If
            .Find.Execute SelTxt
            .Select
        End With
    End Sub
    

    【讨论】:

      【解决方案2】:

      一种廉价的方法是使用书签。在移动文本之前和之后的某个时间点,分别运行 AddBookMark 和 DeleteBookMark。

      Public Sub AddBookMark()
          Dim myDocument As Document
          Set myDocument = ActiveDocument
      
          myDocument.Bookmarks.Add "MySelectedText", Selection
      End Sub
      
      Public Sub DeleteBookMark()
          Dim myDocument As Document
          Set myDocument = ActiveDocument
      
          myDocument.Bookmarks("MySelectedText").Delete
      End Sub
      
      Sub moveRight()
          Dim myDocument As Document
          Set myDocument = ActiveDocument
      
          Selection.Cut
          Selection.moveRight Unit:=wdWord, Count:=1
          Selection.PasteAndFormat (wdFormatOriginalFormatting)
      
          myDocument.Bookmarks("MySelectedText").Select
      End Sub
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-12-23
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多