Find.Execute with confirmation dialog

2019-06-09 04:07发布

问题:

I'm writing a macro in Visual Basic (ugh, I know) to parse documents in Microsoft Word. This is the workflow I'm trying to achieve:

  • Search for a string in the document (equivalent to Edit > Find > Find...).
  • Ask the user if he or she wants to replace the matching string with another string (equivalent to Edit > Find > Replace... > Replace, but with a confirmation dialog before performing the replacement).
  • If yes, do the replacement. If not, go to the next match.

I can do the finding and replacing with the Find.Execute method:

Set myRange = ActiveDocument.Content 
myRange.Find.Execute FindText:="hi", _ 
    ReplaceWith:="hello", Replace:=wdReplaceAll

But I'm not sure how to prompt the user before performing the replacement.

回答1:

You can prompt with a message box, then test the return value and perform the replacement based on that:

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