[英]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.
目标是通过右键单击光标下的单词,单击宏,选择该单词(修剪空格)并将其发送到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. 唯一要做的就是所选单词将自己置于默认的MS-Word搜索对话框中(如果它不活动则打开它),这会自动突出显示文档中的所有实例。 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: 以下是两个期望的步骤:
Thanks 谢谢
Unfortunately, there is no way to fill the search field in the navigation pane using the Word object model. 遗憾的是,无法使用Word对象模型填充导航窗格中的搜索字段。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.