我VBA
为此Word
在右键单击的上下文菜单中添加了一个按钮,该按钮启动了我的应用程序(有效)。
我需要单击的单词将其作为参数传递。我看到我不能使用Selection
,因为右键单击没有选择单词,它给了我光标后面的字母。
根据我所阅读的内容,我可能会查看光标的位置,然后查看单词开始和结束的两侧。
这似乎有效
Selection.Words(1).Text
编辑
更健壮地解释句子的结尾。
Sub FindWord()
Dim rWord As Range
If Selection.Words(1).Text = vbCr Then 'end of sentence
'get last word of sentence
Set rWord = Selection.Words(1).Previous(wdWord)
Else
'get selected word
Set rWord = Selection.Words(1)
End If
'There has to be a better way than this
If rWord.Text = "." Or rWord.Text = "?" Then
Set rWord = rWord.Previous(wdWord)
End If
Debug.Print rWord.Text
End Sub
这是检查光标下单词的最简单方法。
Sub Sample()
Dim pos As Long
'~~> if the cursor is at the end of the word
Selection.MoveEnd Unit:=wdCharacter, Count:=1
Do While Len(Trim(Selection.Text)) = 0
'~~> Move one character behind so that the cursor is
'~~> at the begining or in the middle
Selection.MoveEnd Unit:=wdCharacter, Count:=-1
Loop
'~~> Expand to get the word
Selection.Expand Unit:=wdWord
'~~> Display the word
Debug.Print Selection.Text
End Sub