如何在Word中右键单击下知道单词

时间:2012-08-13 18:44:02

标签: vba ms-word

VBA Word为右键单击的上下文菜单添加了一个按钮,启动了我的应用程序(可以正常运行)。

我需要点击这个词来传递它作为参数。我看到我无法使用Selection,因为右键单击不会选择单词,它会在光标后面给我字母。

根据我所读到的内容,我可以查看光标的位置,然后查看单词开始和结束的两侧。

2 个答案:

答案 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