2017-04-18 31 views
0

我正在嘗試創建兩個快捷鍵,這些快捷鍵可以讓我快速將選定的文字移動到文本中的右側和左側。所選文字應該向左或向右移動一個單詞。 這是我想要做的在文本中移動文字

1)選擇單詞例如「This is」在句子中「this is a tree」 2)按ctrl + alt +右邊的箭頭 3)現在這句話讀作「a this is tree」 4)再次按ctrl alt +箭頭到右邊 5)現在這句話讀作「這棵樹是」

這個想法是取代切割/粘貼步驟,使過程更有效和平滑。 我不知道在VB中,但通過使用Word的宏功能設法接近。

該功能的問題在於所選單詞一旦被粘貼就不再選擇。因此,再次觸發該功能(=將文本移動超過一個單詞)會導致錯誤(我將不得不再次選擇相關文本)。是否有任何方法可以在粘貼後選定的單詞保持選定狀態,以便我可以重複觸發該功能?

非常感謝。

回答

0

您可能想嘗試此解決方案。下面的前兩個步驟應該由您的鍵盤快捷鍵調用。兩者都調用相同的執行子,但具有不同的參數。

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 
0

這樣做的便宜方法是使用書籤。在移動文本之前和之後的某個點,分別運行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