查找.使用确认对话框执行



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

  • 在文档中搜索字符串(相当于 Edit > Find > Find... )。
  • 询问用户是否要将匹配的字符串替换为另一个字符串(相当于 Edit > Find > Replace... > Replace,但在执行替换之前带有确认对话框)。
  • 如果是,请进行更换。如果没有,请转到下一场比赛。

我可以查找并用Find.Execute方法替换:

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

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

您可以使用消息框进行提示,然后测试返回值并基于该值执行替换:

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

最新更新