VBA
Word
为右键单击的上下文菜单添加了一个按钮,启动了我的应用程序(可以正常运行)。
我需要点击这个词来传递它作为参数。我看到我无法使用Selection
,因为右键单击不会选择单词,它会在光标后面给我字母。
根据我所读到的内容,我可以查看光标的位置,然后查看单词开始和结束的两侧。
答案 0 :(得分:3)
这似乎有效
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
答案 1 :(得分:1)
这是检查光标下单词的最简单方法。
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