使用VBA MS-Word打开包含所选单词的搜索对话框

时间:2016-10-04 05:21:55

标签: vba ms-word

我已经加入这些方法来创建一个分配给右键菜单按钮的宏。目标是通过右键单击光标下的单词,单击宏,选择该单词(修剪空格)并将其发送到Word的默认搜索对话框。

Option Explicit
Sub CreateMacro()
    Dim MenuButton As CommandBarButton
    With CommandBars("Text")
        Set MenuButton = .Controls.Add(msoControlButton)
        With MenuButton
            .Caption = "Find word"
            .Style = msoButtonCaption
            .OnAction = "FindWordUnderCursor"
        End With
    End With
End Sub

Sub ResetRightClick()
    Application.CommandBars("Text").Reset
End Sub

Sub FindWordUnderCursor()
    Dim pos As Long
    Dim myRange As Range

    '~~> 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
    If Selection.Characters(Selection.Characters.Count) = " " Then
        Selection.MoveEnd Unit:=wdCharacter, Count:=-1
    End If

    '~~> Display the word
    Debug.Print Selection.Text

End Sub

唯一要做的就是所选单词将自身置于默认的MS-Word搜索对话框中(如果它未激活则打开它),这会自动突出显示文档中的所有事件。当然,如果我右键单击另一个单词并选择宏,则新单词必须替换前一个单词。你能帮忙吗?

以下是两个理想的步骤:

step1 step2

由于

1 个答案:

答案 0 :(得分:0)

不幸的是,无法使用Word对象模型填充导航窗格中的搜索字段。但是,您可以使用一行代码轻松突出显示所有单词:

ActiveDocument.Range.Find.HitHighlight Selection.Range.Text

作为填写导航窗格中搜索框的替代方法,您可以打开搜索对话框(但不会立即突出显示文本):

Dim dlg As Dialog
Set dlg = Application.Dialogs(wdDialogEditFind)
dlg.Find = Selection.Range.Text
dlg.Display
相关问题