我正在尝试创建两个键盘快捷键,这些快捷键允许我在文本中快速向右和向左移动选定的单词。所选文本应向左或向右移动一个单词。 这就是我想要做的事情
1)选择单词,例如“这是”句子“这是一棵树” 2)按例如ctrl + alt +向右箭头 3)句子现在读作“这是树” 4)再次按ctrl alt +箭头向右 5)句子现在读作“这是一棵树”
想法是更换切割/粘贴步骤,使过程更有效,更顺畅。 我对VB不了解,但是通过使用Word的宏功能设法接近。
Sub moveRight()
'moveRight Macro
Selection.Cut
Selection.moveRight Unit:=wdWord, Count:=1
Selection.PasteAndFormat (wdFormatOriginalFormatting)
End Sub
此功能的问题在于粘贴后不再选择所选单词。因此,再次触发该功能(=将文本移动多于一个单词)会导致错误(我将不得不再次选择相关文本)。粘贴后,选择的单词是否仍然有选择,以便我可以重复触发该功能?
非常感谢。
答案 0 :(得分: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
答案 1 :(得分: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