简体   繁体   中英

Open search dialog with a selected word with VBA MS-Word

I've joined these methods to create a macro to be assigned to a right-click menu button. The objective is to select the word under the cursor with the right-click, click on the macro, which selects that word (trimming spaces) and sends it to the default search-dialog of 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

The only thing left to achieve is that the selected word puts itself in the default MS-Word search dialog box (or open it if it's not active), which automatically highlights all the occurrences in the document. Of course, if I right-click another word and select the macro, the new word has to substitute the previous one. Can you help, please?

Here are the two desired steps:

step1 step2

Thanks

Unfortunately, there is no way to fill the search field in the navigation pane using the Word object model. However, you are able to highlight all occurrences of a word easily using a single line of code:

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

As an alternative to filling the search box in the navigation pane, you may open the search dialog box (but you won't get the immediate highlight of text):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM