【问题标题】:Open search dialog with a selected word with VBA MS-Word使用 VBA MS-Word 打开带有所选单词的搜索对话框
【发布时间】:2016-10-04 15:09:12
【问题描述】:

我已经加入了这些方法来创建一个宏以分配给右键单击菜单按钮。目标是通过右键单击选择光标下的单词,单击宏,选择该单词(修剪空格)并将其发送到 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

谢谢

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 单行代码就可以解决问题,我只需“撤消”操作即可摆脱突出显示。当然,整个方法并不完美(我希望 Word 内置它以帮助作者查找重复项。如果您愿意,我正在使用它和我编写的另一个宏来识别文本中的重复单词不客气,请在我的问题中查看。
    • 糟糕,我注意到如果我选择撤消,此操作会撤消突出显示,但也会撤消之前执行的操作。也就是说,如果我更正了一个单词并点击撤消,则突出显示会消失,但更正会恢复。有什么办法规避这个问题吗?
    • 哦,没关系,如果我在任何地方点击一个空格,高亮就会消失。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多