Find.Execute 带有确认对话框

Find.Execute with confirmation dialog

我正在用 Visual Basic(呃,我知道)编写一个宏来解析 Microsoft Word 中的文档。这是我要实现的工作流程:

我可以用 Find.Execute method:

进行查找和替换
Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="hi", _ 
    ReplaceWith:="hello", Replace:=wdReplaceAll

但我不确定如何在执行替换之前提示用户。

您可以用消息框提示,然后测试 return 值并根据该值执行替换:

Private Sub PromptForReplace()

    Dim myRange As Range

    Set myRange = ActiveDocument.Content
    myRange.Find.ClearFormatting
    myRange.Find.MatchWildcards = True

    Dim cached As Long
    cached = myRange.End
    Do While myRange.Find.Execute("hi")
        myRange.Select
        If MsgBox("Replace " & myRange.Find.Text & "?", vbYesNo) = vbYes Then
            myRange.Text = "hello"
        End If
        myRange.Start = myRange.Start + Len(myRange.Find.Text)
        myRange.End = cached
    Loop

End Sub